Viniyo Shouta Viniyo Shouta - 21 days ago 7
PHP Question

Key auto assigned on sequential array using integer keys

I'm coming from C++ and learning PHP at the moment.

When using arrays with key assignment I noticed that if you add an element to the array without specifying the key it'll auto-assign it.

Is that undefined behavior or PHP handles that?

$var = array( 1 => "The", 2 => "Rabbit", 3 => "Hole" );
$var[] = "Goes"; //add elements without specifying the key
$var[] = "Down";

print_r($var);


will output:

Array ( [1] = The [2] = Rabbit [3] = Hole [4] = Goes [5] = Down )


By using char keys and adding without specifying the key it'll add to [0]

$var2 = array ( 'a' => "All", 'b' => "The", 'c' => "Single" );
$var2[] = "Ladies";
print_r($var2);


will output:

Array ( [a] = All [b] = The [c] = Single [0] = Ladies )

Answer

The behaviour is defined by the PHP specification. In case you insert a new element without specifying a key:

If the array already contains at least one integer key, the largest of these keys will be taken, incremented, and used as a new key upon insertion.

If the array does not contain an integer key, the automatically assigned key will be 0.

See the PHP documentation.