PHP
Reindex and Reset Numeric Keys of a PHP Array
Discover how to reset an array's numeric keys, ensuring they start from zero and are sequential after elements have been removed, filtered, or reordered in PHP.
<?php
/**
* Resets the numeric keys of an array to be sequential, starting from 0.
*
* @param array $array The input array.
* @return array The reindexed array.
*/
function reindex_array_numeric(array $array): array
{
return array_values($array);
}
// Example usage 1: After removing elements
$data = ['a', 'b', 'c', 'd', 'e'];
unset($data[1]); // Remove 'b'
unset($data[3]); // Remove 'd'
// $data is now: [0 => 'a', 2 => 'c', 4 => 'e']
print_r($data);
$reindexedData = reindex_array_numeric($data);
// Expected: ['a', 'c', 'e'] (keys: 0, 1, 2)
print_r($reindexedData);
// Example usage 2: With an associative array (keys will be discarded for values)
$associative = [
'user_id' => 123,
'username' => 'john.doe',
'email' => '[email protected]'
];
$reindexedAssociative = reindex_array_numeric($associative);
// Expected: [0 => 123, 1 => 'john.doe', 2 => '[email protected]']
print_r($reindexedAssociative);
// Example usage 3: After filtering
$numbers = [1, 5, 8, 12, 15];
$filteredNumbers = array_filter($numbers, fn($n) => $n > 10);
// $filteredNumbers is now: [3 => 12, 4 => 15]
print_r($filteredNumbers);
$reindexedFilteredNumbers = reindex_array_numeric($filteredNumbers);
// Expected: [0 => 12, 1 => 15]
print_r($reindexedFilteredNumbers);
?>
How it works: When elements are removed from a PHP array using `unset()`, or after filtering with `array_filter()`, the original numeric keys remain. This can lead to non-sequential keys, which might cause issues in loops or when converting to JSON arrays. The `reindex_array_numeric` function, leveraging `array_values()`, efficiently resets these keys to be sequential, starting from 0. This ensures a clean, standard array structure suitable for many web development tasks.