Today I discovered a quite disturbing fact about the way php handles array indexing. Talk about bad language design…
When using strings that contain only numbers (and don’t start with ’0′ (zero)) as indexes, they are automatically and inevitably converted to integers. For example:
$arr = array();
$b = '1234';
$arr['xxxx'] = 'y';
$arr[$b] = 'whatever';
foreach ($arr as $key => $value) {
echo gettype($key)."n";
}
The expected output would be:
string string
But it is:
string integer
Oh, wow. This is not a big thing, right? PHP does this all the time, converting numeric strings to integers and vica-versa. Right, and it’s very convenient sometimes, but array indexing is something that should be handled very sensitively. For example I discovered this inner workings of PHP while debugging a seemingly mysterious bug in my code. I was filling up an associative array keyed by strings coming from a VARCHAR field in MySQL. Nothing fancy so far. Some of these strings contained only numbers. Later on, I used some code like:
foreach ($my_arr as $str_key => $some_value) {
if (strpos($some_string, $str_key) !== false) {
.
.
.
}
}
And it started producing strange results – strings being matched which evidently didn’t match – wtf is going on? Reading the docs of strpos I found that if the needle is an integer, it’s converted to characters by their ordinal values. But where did those integers come from? ARRGHH, those pesky autoconverted array keys!
To fix it:
foreach ($my_arr as $str_key => $some_value) {
if (strpos($some_string, (string)$str_key) !== false) {
.
.
.
}
}
So if I ever need some facts to use in the “why I hate php” type arguments, this will be in my pocket.

Facebook
Google
LinkedIn
Twitter
RSS
Pingback: ??????? » [Web] ????
Pingback: Pinderkent: Programming languages should not try to guess the programmer's intentions.
Pingback: blog@iamnolegend.com [ochronus] » A serious PHP design flaw - watch out!