Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does PHP have autovivification?

Searching PHP.net for autovivification gives no results. At the time of writing, Wikipedia claims that only Perl has it. There are no clearly definitive results when searching Google for "php autovivification".

This PHP code runs fine:

$test['a'][4][6]['b'] = "hello world";
var_dump($test);

array
  'a' => 
    array
      4 => 
        array
          'b' => 
            array
              ...

Can anyone provide a canonical answer (preferably with references) that PHP does have this feature, and any details such as the version it was introduced in, quirks, shortcuts etc?

like image 796
Ollie Glass Avatar asked May 11 '11 12:05

Ollie Glass


1 Answers

Yes, PHP does have autovivification (and has had it for a long time), although it isn't referenced by that terminology. PHP.net states:

An existing array can be modified by explicitly setting values in it.

This is done by assigning values to the array, specifying the key in brackets. The key can also be omitted, resulting in an empty pair of brackets ([]).

$arr[key] = value;
$arr[] = value;
// key may be an integer or string
// value may be any value of any type

If $arr doesn't exist yet, it will be created, so this is also an alternative way to create an array.

However, the documentation states that if you try to access the value of an unset array (or key), it will return an error:

Attempting to access an array key which has not been defined is the same as accessing any other undefined variable: an E_NOTICE-level error message will be issued, and the result will be NULL.

I have tracked down my old PHP3 manual, which states this:

You can also create an array by simply adding values to the array.

$a[] = "hello";
like image 92
Kelly Avatar answered Sep 24 '22 06:09

Kelly