6

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?

Madhur Bhaiya
  • 28,155
  • 10
  • 49
  • 57

3 Answers3

17

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
Madhur Bhaiya
  • 28,155
  • 10
  • 49
  • 57
2

Use array_slice() instead that select special part of array

$newCars = array_slice($cars, 1)

Check result in demo

Mohammad
  • 21,175
  • 15
  • 55
  • 84
0

Assuming you always want to remove the first element from the array, the array_shift function returns the first element and also reindexes the rest of the array.

$cars = array("Volvo", "BMW", "Toyota", "Mercedes");
$first_car = array_shift($cars);
var_dump($first_car);
// string(5) "Volvo"
var_dump($cars)
// array(3) {
//  [0] =>
//  string(3) "BMW"
//  [1] =>
//  string(6) "Toyota"
//  [2] =>
//  string(8) "Mercedes"
//}
Matt Raines
  • 4,149
  • 8
  • 31
  • 34