2

I've turned on all error reporting to clean up some undefined indexes, just to make the app I'm making more neat. I've noticed a curious behavior:

Let's say I have the following array: $a = array('test' => false, 'foo' => 'bar')

If I do if ($a['nothere']), I properly get a notice of Undefined index: nothere.

However, if I do if ($a['test']['nothere']), I don't get a notice. At all. Despite nothere definitely not being an index in $a['test'].

Now, if I do $a['test'] = array('baz' => 'poof'), then running if ($a['test']['nothere']) does throw a notice.

Does undefined index checking not check for indexes in an empty array? This is on PHP 5.2.8.

Piskvor left the building
  • 91,498
  • 46
  • 177
  • 222
Andrew
  • 5,095
  • 6
  • 42
  • 48
  • 1
    it's most likely because [] string access syntax and type juggling. `$a = array('test' => array(), 'foo' => 'bar')` would produce you an error – Your Common Sense Feb 07 '11 at 16:03
  • hah, thanks for editing out the curious construction caused by a previous copyedit, @Piskvor. :P – Andrew Feb 07 '11 at 16:03
  • Ah, so you're suggesting, when it does `if($a['test']['nothere'])`, it gets as far as `if($a['test'])`, sees that resolve to `false`, and short circuits? – Andrew Feb 07 '11 at 16:04

1 Answers1

5

it's because of tricky type juggling. $a['test'] being cast to [empty] string and then 'nowhere' being cast to 0 and then PHP tries to look for 0's symbol in the empty string. It becomes substring operation, not variable lookup, so, no error raised.

Gee, a man says the same: http://php.net/manual/en/language.types.type-juggling.php

A curious example from my experience:
Being requested via hyperlink index.php?sname=p_edit&page=0, a code

if (isset($_GET['sname'])) { $page['current'] = $_GET['sname'].'.php'; };
echo $page['current'];

produces just one letter "p"

I counted 6 steps and 2 type casts which ends up with such a result.
(Hint: a poor fellow who asked this question had register globals on)

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345