Array push creates new index 0 1 2 string php

A classic PHP gotcha!

In PHP, when you use the push() method on an array, it does not automatically increment the indices of the existing elements. Instead, it adds a new element to the end of the array and assigns it the next available index.

For example:

$array = array('a', 'b', 'c');
$array[] = 'd'; // equivalent to $array = array_merge($array, array('d'));
print_r($array);

Output:

Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
)

As you can see, the new element 'd' is assigned the index 3, not 2. The indices of the existing elements remain the same.

If you want to maintain the original indices and add a new element at the beginning of the array, you can use the array_unshift() function:

$array = array('a', 'b', 'c');
array_unshift($array, 'd');
print_r($array);

Output:

Array
(
    [0] => d
    [1] => a
    [2] => b
    [3] => c
)

Alternatively, you can use the array_merge() function to merge the original array with a new array containing the new element:

$array = array('a', 'b', 'c');
$array = array_merge(array('d'), $array);
print_r($array);

Output:

Array
(
    [0] => d
    [1] => a
    [2] => b
    [3] => c
)