PHP associative arrays - how to treat an integer as a string
I have a simple associative array.
$a = array("a"=>"b", "c"=>"d"); I want to check if the key "1" exists in the array, for example
isset($a["1"]); This string is treated as an integer, so
echo $a["1"]; //prints "d" How do I get it to treat it as a string?
I do not want to use array_key_exists or in_array, because my benchmarking shows isset will be much faster.
It does not seem that you can do what you want. from http://us.php.net/manual/en/language.types.array.php :
The key can be an integer or a string. If the key is a standard representation of an integer, it will be interpreted as such (i.e., "8" will be interpreted as 8, and "08" will be interpreted as "08").
You may have to use the Fosco suggestion for prefixing all your keys with something. If you use the same prefix for each key, it doesnβt matter if you analyze text that can contain words and numbers, put the same prefix on anything.
isset ($ a ["1"]) | isset ($ a [1])?
Or just isset ($ a [1])
Or even isset ($ a [intval (1)]) is 1000% sure.
if echo $ a ['1'] prints d, then your array has more elements than you understand.
see the var_dump ($ a) and print_r ($ a) functions to help you debug your code.