Search code examples
phparraysunsetundefined-index

How can I delete my undefined indexes in the array and move the others to position 0?


I'm having an array I'm unsetting.

In my example, I'm unsetting the first object in the array.

Array ( [0] => 1 [1] => 2 [2] => 5 [3] => 6 [4] => 7 [5] => 8 )

unset(Array[0]);

It gives me back:

Array ( [1] => 2 [2] => 5 [3] => 6 [4] => 7 [5] => 8 )

Index 0 is gone. How can I make the array start from index 0 that I would get this back?

Array ( [0] => 2 [1] => 5 [2] => 6 [3] => 7 [4] => 8 )

Solution

  • You could use array_values() to reindex the array:

    unset($array[0]);
    $array = array_values($array);