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.
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)