Search code examples
phparraysunset

Reset PHP array index to start from 0 after unset operation


I have an array

$cars = array("Volvo", "BMW", "Toyota", "Mercedes");

I wanted to remove first element "Volvo" and i use this

unset($cars[0]);

Now i have an array like this:

Array
(   
    [1] Bmw
    [2] Toyota
    [3] Mercedes
)

But i want to my array begins again with zero, to be like this:

Array
(
    [0] Bmw
    [1] Toyota
    [2] Mercedes
)

How to do it?


Solution

  • Use array_values function to reset the array, after unset operation.

    Note that, this method will work for all the cases, which include unsetting any index key from the array (beginning / middle / end).

    array_values() returns all the values from the array and indexes the array numerically.

    Try (Rextester DEMO):

    $cars = array("Volvo", "BMW", "Toyota", "Mercedes");
    unset($cars[0]);
    $cars = array_values($cars);
    var_dump($cars); // check and display the array