How to Reindex an Array in PHP?

Problem:

You have an indexed array. Some values from this array are removed. See the following array. Now, you want to re-index the array, meaning serialize the keys staring keys from 0 and incrementing by 1. 

$cars = array(
    2 => “Alco”,
    3 => “Alesia”,
    4 => “BAZ”,
    7 => “BMW”,
    10 => “Chery”,
    11 => “Eagle”
)

Solution:

array_values() function will help you re-index the array and sort the keys from 0 serially. See the following example-

<pre>
<?php
$cars = array(
    2 => "Alco",
    3 => "Alesia",
    4 => "BAZ",
    7 => "BMW",
    10 => "Chery",
    11 => "Eagle"
);

$cars = array_values($cars);
print_r($cars);
?>
</pre>

 

[wpdm_file id=102]

Output:

Array(
     [0] => Alco
     [1] => Alesia
     [2] => BAZ
     [3] => BMW
     [4] => Chery
     [5] => Eagle
)