PHP
Re-index a PHP Array Numerically
Learn how to reset and re-index the keys of a PHP array to a sequential, zero-based numeric order using array_values(), essential after element removal.
<?php
$data = ['id' => 1, 'name' => 'Alice', 'age' => 30];
unset($data['id']); // Remove an element, leaving a non-sequential key
print_r($data);
/* Output:
Array
(
[name] => Alice
[age] => 30
)
*/
$reindexedData = array_values($data);
print_r($reindexedData);
/* Output:
Array
(
[0] => Alice
[1] => 30
)
*/
// Example with a sparse numerical array
$sparseArray = [0 => 'first', 2 => 'third', 4 => 'fifth'];
$compactedArray = array_values($sparseArray);
print_r($compactedArray);
/* Output:
Array
(
[0] => first
[1] => third
[2] => fifth
)
*/
How it works: When elements are removed from an array using `unset()`, or if an array has non-sequential numerical keys, the array's keys can become sparse. The `array_values()` function returns all the values from an array and re-indexes them numerically, starting from 0. This creates a new array with a clean, sequential integer index, which is often desirable for consistent array processing.