phpautovivification

PHP autovivification


Update: My original intention for this question was to determine if PHP actually has this feature. This has been lost in the answers' focus on the scalar issue. Please see this new question instead: "Does PHP have autovivification?" This question is left here for reference.

According to Wikipedia, PHP doesn't have autovivification, yet this code works:

$test['a']['b'] = 1;
$test['a']['c'] = 1;
$test['b']['b'] = 1;
$test['b']['c'] = 1;

var_dump($test);

Output:

array
  'a' => 
    array
      'b' => int 1
      'c' => int 1
  'b' => 
    array
      'b' => int 1
      'c' => int 1

I found that this code works too:

$test['a'][4] = 1;
$test['b'][4]['f'] = 3;

But adding this line causes an warning ("Warning: Cannot use a scalar value as an array")

$test['a'][4]['f'] = 3;

What's going on here? Why does it fail when I add the associative element after the index? Is this 'true' Perl-like autovivification, or some variation of it, or something else?

Edit: oh, I see the error with the scalar now, oops! These work as expected:

$test['a'][4]['a'] = 1;
$test['a'][4]['b'] = 2;
$test['a'][5]['c'] = 3;
$test['a'][8]['d'] = 4;

So, php does have autovivification? Searching Google for "php autovivification" doesn't bring up a canonical answer or example of it.


Solution

  • From the PHP manual on the square bracket syntax:

    $arr[] = value;

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

    With your example:

    $test['a'][4] = 1;
    

    Since $test and $test['a'] don't currently exist; they are both created as arrays.

    $test['b'][4]['f'] = 3;
    

    $test['b'] and $test['b'][4] don't currently exist; they are both created as arrays.

    $test['a'][4]['f'] = 3;
    

    $test['a'][4] does exist, but it is an integer (1). This is the "scalar value" that cannot be used as an array. You can't use the square bracket [] syntax on number values; it doesn't convert an existing value to an array.