1

I thought I knew everything about php until I bumped into this:

$foo = 'hello';
isset($foo['a']);     // returns false - OK
isset($foo['a']['b']; // returns false - OK
isset($foo['a'][0]);  // returns true! WTF?!

Could anybody explain me the result of the 4th line? Tested with php 5.5.36.

3
  • var_dump($foo['a'][0]) Commented Aug 28, 2016 at 12:04
  • also found on phpfiddle.org with this code $foo = 'hello'; echo isset($foo['a'])? 'yes 2' : ""; // returns false - OK echo isset($foo['a']['b'])? 'yes 3' : ""; // returns false - OK echo isset($foo['a'][0]) ? 'yes 4' : ""; Commented Aug 28, 2016 at 12:05
  • but foo is string not array Commented Aug 28, 2016 at 13:07

1 Answer 1

5

Well, the question is somewhat misleading, because isset returns true for any variable that is not null. Since $foo is a string, and not an array, $foo["a"] gives an Illegal string offset warning. PHP assumes that you meant to cast "a" as an integer offset and does that implicitly, turning $foo["a"] into $foo[0] which gives you the string "h" (the first offset of the string). Since the return value is another string the expression becomes "h"[0], which is just "h" again.

So in other words, $foo["a"][0] where $foo = "hello" is the same thing as $foo[0][0] which gives us "h".

But as far as non-existing array keys, isset would definitely return false since a non-existing key leads to a non-existing value which is implicitly null.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.