Strange behavior with isset() returning true for an Array Key that does NOT exist

这一生的挚爱 提交于 2019-11-27 08:14:01

问题


I have the following array called $fruits:

Array
(
    [response] => Array
        (
            [errormessage] => banana
        )  

    [blah] => Array
        (
            [blah1] => blahblah1
            [blah2] => blahblah2
            [blah3] => blahblah3
            [blah4] => blahblah4
        )  

)

Yet when I do:

isset($fruits['response']['errormessage']['orange'])

It returns true!

What on earth would cause such a strange behavior and how can I fix this?

Thanks!


回答1:


[n] is also a way to access characters in a string:

$fruits['response']['errormessage']['orange']
==
$fruits['response']['errormessage'][0] // cast to int
==
b (the first character, at position 0) of 'banana'

Use array_key_exists, possibly in combination with is_array.




回答2:


It just boils down to PHP's crazy type system.

$fruits['response']['errormessage'] is the string 'banana', so you're attempting to access a character in that string by the ['orange'] index.

The string 'orange' is converted to an integer for the purposes of indexing, so it becomes 0, as in $fruits['response']['errormessage'][0]. The 0th index of a string is the first character of the string, so for non-empty strings it's essentially set. Thus isset() returns true.

I don't know what you're trying to do in the first place so I can't offer any "fix" for this. It's by design.




回答3:


to fix

if (is_array($fruits['response']['errormessage']) 
    && isset($fruits['response']['errormessage']['orange'])) { .. }


来源:https://stackoverflow.com/questions/9132715/strange-behavior-with-isset-returning-true-for-an-array-key-that-does-not-exis

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!