Last Updated: February 25, 2016
·
1.665K
· rican7

PHP Array Accessor Gotcha / Unexpected behavior

Ok, so I've been programming in PHP since I was 15 (holy shit! 8 years!!!), and since I normally check variables before using them, I have yet to ever notice this behavior in my code:

Code:

<?php

error_reporting(-1);

$null = null;
$arr = array();
$str = 'string';
$int = 7;
$dbl = 7.3;
$bool = true;
$obj = new stdClass();

echo $null['nope'];
echo $null['nope']['sure'];

echo $arr['nope'];
echo $arr['nope']['sure'];

echo $str['nope'];
echo $str['nope']['sure'];

echo $int['nope'];
echo $int['nope']['sure'];

echo $dbl['nope'];
echo $dbl['nope']['sure'];

echo $bool['nope'];
echo $bool['nope']['sure'];

echo $obj['nope'];
echo $obj['nope']['sure'];

Output:

Notice: Undefined index: nope in /in/dNmX4 on line 16

Notice: Undefined index: nope in /in/dNmX4 on line 17

Warning: Illegal string offset 'nope' in /in/dNmX4 on line 19
s
Warning: Illegal string offset 'nope' in /in/dNmX4 on line 20

Warning: Illegal string offset 'sure' in /in/dNmX4 on line 20
s
Fatal error: Cannot use object of type stdClass as array in /in/dNmX4 on line 31

Process exited with code 255.

Yea.... so I guess you can just YOLO and access null's, integers, floats, and even booleans as arrays, and they won't so much as even raise a strict notice...
WAT!?!!

In case you're curious about how it's handled in different versions, you can see the output in multiple PHP versions here:
http://3v4l.org/dNmX4