数组:第四维,isset 返回不可靠
有谁知道这段代码怎么会与 yahoo
相呼应?显然没有第四个数组带有键“something”,但它一直认为是这样的。漏洞?特征?
$array = array('a' => array('b' => array('c' => 'test')));
echo '<pre>';
var_dump($array);
echo '</pre>';
if (isset($array['a']['b']['c']['something'])) {
echo 'yahoo';
}
Does anybody know, how it can be, that this code echoes yahoo
? There is clearly no 4th array with the key 'something', but it keeps thinking it's like that. Bug? Feature?
$array = array('a' => array('b' => array('c' => 'test')));
echo '<pre>';
var_dump($array);
echo '</pre>';
if (isset($array['a']['b']['c']['something'])) {
echo 'yahoo';
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为 PHP 认为您正在检查字符串“test”的“something”位置。请记住,字符串是字符数组。尝试回显 $array['a']['b']['c']['something']。
::编辑::
我解释了它,我并没有说它有道理。 :P
Because PHP thinks you are checking the 'something'th place of the string 'test'. Remember, strings are arrays of characters. try to echo $array['a']['b']['c']['something'].
::EDIT::
I Explained it, I didn't say it made sense. :P
这里讨论了 PHP 在这个问题上的行为并提供了一个完全适合您问题的解决方案。
Here has discussed the behavior of PHP in this issue and provides a solution that is exactly for your problem.
您想要使用
is_array($array['a']['b']['c'])
而不是isset($array['a']['b ']['c']['something'])
在这种情况下,或者可能是两者的巧妙组合,以确保在检查时未设置时不会收到任何错误如果它是一个数组。像这样的东西:
You'd want to use
is_array($array['a']['b']['c'])
rather thanisset($array['a']['b']['c']['something'])
in this case, or maybe a crafty combination of the two to make sure you don't get any errors if it's not set when you're checking to see if it's an array.Something like: