$ar['123'] = "test";
var_dump($ar); // Key is int
$ar2['123a'] = "test";
var_dump($ar2); //Key is string
Why is this happening ? Is there a work around ? I want to have a key of numbers as a string not as an integer.
Thnx
$ar['123'] = "test";
var_dump($ar); // Key is int
$ar2['123a'] = "test";
var_dump($ar2); //Key is string
Why is this happening ? Is there a work around ? I want to have a key of numbers as a string not as an integer.
Thnx
you can use "123" as a number when needed. and also you can substr or strlen "123" as string. php variables are flexible.
You don't have to worry about data types in PHP, the conversions are done automatically for you.
Just to give you an example, the following code:
<?php
if("10" == 10)
{
echo "It's equal!";
}
?>
Will actually output:
It's equal!
You can see it in action here: http://ideone.com/aayLx
Bottom line is: don't worry about it, PHP will treat it as a string when you need it to.
You can typecast the key to a string but it will eventually be converted to an integer due to PHP's loose-typing. From the manual http://php.net/manual/en/language.types.array.php
A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. "8" will be interpreted as 8, while "08" will be interpreted as "08").
Strings are automatically casted to integers when the string is an integer. See http://php.net/manual/en/language.types.array.php for more information on this.
To work around this, you must prepend the integer with a 0:
$ar2["0123"] will use '123' as the key