How to Reindex a PHP Array?

You can re-index an array in PHP in the following ways:

Using array_values()

The array_values() function returns an indexed array of all the values from the specified array. For example:

$arr = [ 2 => 'foo', 6 => 'bar', 4 => 'baz' ];
$newArr = array_values($arr);

var_dump($newArr); // [0 => 'foo', 1 => 'bar', 2 => 'baz']

Using the Splat Operator

You can use the splat operator (...) to unpack the array into a new array like so:

$arr = [ 2 => 'foo', 6 => 'bar', 4 => 'baz' ];
$newArr = [ ...$arr ];

var_dump($newArr); // [0 => 'foo', 1 => 'bar', 2 => 'baz']

Please note that using the splat operator (...) might not be performant with large arrays.

Using a Loop

You can use a simple loop, such as a for loop, to iterate over the original array and add values from it to a new array:

$arr = [ 2 => 'foo', 4 => 'bar', 6 => 'baz' ];
$newArr = [];

foreach ($arr as $item) {
    $newArr[] = $item;
}

var_dump($newArr); // [0 => 'foo', 1 => 'bar', 2 => 'baz']

This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.