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

I have the following array called $fruits :

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

But when I do this:

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

It returns true !

What can cause such strange behavior and how can I fix it?

Thanks!

+2
source share
3 answers

[n] 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 .

+6
source

It just comes down to a crazy PHP type system.

$fruits['response']['errormessage'] is the string 'banana' , so you are trying to access the character in this string by the index ['orange'] .

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

I don’t know what you are trying to do first, so I can’t offer any “fixes” for this. This is by design.

+11
source

to fix it

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

All Articles