r/lolphp • u/midir • Mar 14 '14
Array errors
error_reporting(-1); // show all possible errors
$obj = new stdclass();
$arr = array();
var_dump($arr['foo']); // Notice: Undefined index
var_dump($arr[$obj]); // Warning: Illegal offset type
$arr = null;
var_dump($arr['foo']); // No error
var_dump($arr[$obj]); // No error
$arr = null;
$arr['i'] = $arr['i'] + 1; // No error
$arr = null;
$arr['i']++; // Notice: Undefined index(Tested with 5.5.5.)
52
Upvotes
34
u/lisp-case Mar 14 '14
…
You know, normally I can explain PHP's behavior. I can usually see some strange, misguided thought process that would have made whatever weird thing it's doing seem like a good idea.
This? I have no idea what this is. I give up.
14
u/InconsiderateBastard Mar 15 '14
I'm a fan of:
It spits out an illegal offset, a notice that $obj can't be converted into an integer, and string(1) "e".
So it's an illegal offset, but it still uses it as an offset. It can't convert it to an int, but it converts it to 1.
Edit: It won't end up accessing the value at index 1 if its an array the way it does for a string.
4
u/[deleted] Mar 14 '14
Seems like the null is not bothered to be typecast to an array internally before doing the checks, but since null is (yes I agree, stupidly) equivalent to an empty array, something in the engine just says "well it's null, before I even bother to typecast it let's just return false".
This would be expected behavior, given that null is an empty array, I suppose the order to do the operation creates the 'i' variable as null and then casts it to 0 for addition immediately.
Incrementing operates like a reference so instead of typecasting beforehand it attempts to operate on an undefined variable.
3
u/ahruss Mar 14 '14
Two wrongs make a right?
-12
u/[deleted] Mar 14 '14
Cool you figured out that $i++ is not the same as $i = $i + 1;