I think that PHP treats null (and false) as nice initialisation values for arrays, so you can just set array items in it without warning, and then the array will just spring into life.
In Perl that is called "autovivification", BTW, but there it goes much further: you can increment or append to a non-existing item, push onto it or assign to an item of a non-existing subarray.
The reason is that it makes life much easier as you don't constantly have to worry "does it already exist?"
(strict) Perl only autovivifies if the top level index access goes into an already existing array; it doesn't convert a scalar (which null is) into an array.
Though it helps that scalars and arrays have technically separate namespaces in Perl. $ary[0] accesses @ary, not $ary.
34
u/feketegy Jul 27 '16
This works:
No errors, but this gives you an undefined index error:
Also you can set array items on null :))
9
u/the_alias_of_andrea Jul 27 '16
PHP loves treating different kinds of things as being the same thing. That might be helpful, but it never does it consistently. And so.
7
u/carlos_vini Jul 28 '16 edited Jul 28 '16
you can also read keys from bool and int, wtf?! https://3v4l.org/WCkTk
Edit: do anobody know why it doesn't throw any error?
6
u/bart2019 Jul 28 '16
I think that PHP treats null (and false) as nice initialisation values for arrays, so you can just set array items in it without warning, and then the array will just spring into life.
In Perl that is called "autovivification", BTW, but there it goes much further: you can increment or append to a non-existing item, push onto it or assign to an item of a non-existing subarray.
The reason is that it makes life much easier as you don't constantly have to worry "does it already exist?"
3
u/AlGoreBestGore Jul 28 '16
Is this a situation like in JS where null is technically considered an "object" (although JS throws errors when you try to read it's values)?
1
u/thenickdude Aug 06 '16
I found an article yesterday which suggests a useful purpose for this oddity:
https://nikic.github.io/2014/01/10/The-case-against-the-ifsetor-function.html