How to Reindex a PHP Array?

Learn how to reindex a numerically indexed 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']

Hope you found this post useful. It was published (and was last revised ). Please show your love and support by sharing this post.