views:

457

answers:

3

I ran into this bug where an element of an array, if its index is the string "0", is inaccessible.

It's not a bug with unserialize, either, as this occurred in my code without invoking it.

$arr = unserialize('a:1:{s:1:"0";i:5;}');
var_dump($arr["0"]); //should be 5, but is NULL
var_dump($arr[0]);   //maybe this would work?  no. NULL

Am I doing something wrong here? How do I access this element of the array?

A: 

Actually, the code in your question yields

int(5)
Draemon
Which version? I can reproduce John's behavior
Vinko Vrsalovic
"5.2.6-2+b1 with Suhosin-Patch 0.9.6.2"on debian
Draemon
+1  A: 

use var_dump on the structure to see how it's represented . maybe that will help. I was doing the same thing in Perl when I had problems like this with Data::Dumper

xxxxxxx
Sage advice. Investigate first!
Draemon
I did that, but it is indeed a bug on php < 5.2.5
Vinko Vrsalovic
+6  A: 

Yes, it looks as though it is a bug, related to PHPs automatic conversion of strings to integers. More information is available here: http://bugs.php.net/bug.php?id=43614

var_dump( $arr ); // => array(1) { ["0"]=>  int(5) } 
$arr2["0"]=5;
var_dump($arr2); // => array(1) { [0]=>  int(5) } 
print serialize($arr2); // a:1:{i:0;i:5;}

So it seems that older versions of PHP5 don't perform the string index to integer index conversion in unserialize.

This bug was reported in PHP 5.2.5, and is fixed in PHP 5.2.6 (see http://www.php.net/ChangeLog-5.php#5.2.6).

MegaHAL
Doesn't say when it was fixed, but obviously before the version I'm using :)
Draemon
Winner. Thanks.Now can we change the title back to "Is this a bug in PHP?" or something along those lines
Um... I'm using 5.2.5, and it's broken. Do you mean it's fixed in 5.2.6?
how can bugs this fundamental be left out until version 5.2.6 ? that's just mind blowing
xxxxxxx
Sorry, I think 5.2.5 is the version the bug was reported against :(
MegaHAL
They have to be found and reported to be fixed :)
Vinko Vrsalovic