这是PHP数组访问的错误吗?

时间:2021-05-29 21:28:59

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

我遇到了这个错误,如果数组的索引是字符串“0”,那么数组的元素是不可访问的。

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

这也不是unserialize的错误,因为这在我的代码中没有调用它。

$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?

我在这里做错了吗?如何访问数组的这个元素?

3 个解决方案

#1


6  

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

是的,它看起来好像是一个错误,与PHP自动将字符串转换为整数有关。有关更多信息,请访问: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.

因此,似乎旧版本的PHP5在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).

这个错误在PHP 5.2.5中报告,并在PHP 5.2.6中修复(参见http://www.php.net/ChangeLog-5.php#5.2.6)。

#2


1  

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

在结构上使用var_dump来查看它的表示方式。也许这会有所帮助。当我使用Data :: Dumper遇到这样的问题时,我在Perl中做了同样的事情

#3


0  

Actually, the code in your question yields

实际上,你问题中的代码会产生

int(5)

#1


6  

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

是的,它看起来好像是一个错误,与PHP自动将字符串转换为整数有关。有关更多信息,请访问: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.

因此,似乎旧版本的PHP5在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).

这个错误在PHP 5.2.5中报告,并在PHP 5.2.6中修复(参见http://www.php.net/ChangeLog-5.php#5.2.6)。

#2


1  

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

在结构上使用var_dump来查看它的表示方式。也许这会有所帮助。当我使用Data :: Dumper遇到这样的问题时,我在Perl中做了同样的事情

#3


0  

Actually, the code in your question yields

实际上,你问题中的代码会产生

int(5)