Reset PHP array index to start from 0 after unset operation [duplicate]
Asked Answered
C

3

10

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?

Caudill answered 6/10, 2018 at 10:47 Comment(0)
Q
22

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
Quadriplegia answered 6/10, 2018 at 10:49 Comment(0)
C
2

Use array_slice() instead that select special part of array

$newCars = array_slice($cars, 1)

Check result in demo

Connote answered 6/10, 2018 at 10:53 Comment(0)
H
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"
//}
Hoyden answered 6/10, 2018 at 14:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.