How to Reindex a PHP Array?

Learn how to reindex a numerically indexed PHP array

In PHP you can reindex an array by using the array_values() function like so:

$arr = [3 => 'foo', 6 => 'bar', 4 => 'baz'];
$reindexArr = array_values($filteredArr);

echo print_r($reindexArr, true); // [0 => 'foo', 1 => 'bar', 2 => 'baz']

Alternatively, you may also use the splat operator (...) to unpack the array into a new array like so:

$arr = [3 => 'foo', 6 => 'bar', 4 => 'baz'];
$reindexArr = [...$arr];

echo print_r($reindexArr, true); // [0 => 'foo', 1 => 'bar', 2 => 'baz']

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

As you can see from the examples above, the array elements are indexed according to the order in which they appear in the original array (and not based on the keys).


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