PHP

Re-index Numeric Array Keys After Filtering or Modification

Learn how to easily reset and re-index the numeric keys of an array in PHP, ensuring a contiguous sequence after elements have been removed or reordered.

<?php

$items = ['apple', 'banana', 'orange', 'grape', 'kiwi'];

// Simulate filtering: remove 'orange'
unset($items[2]);

print_r($items);
// Output shows that key 2 is missing:
// Array
// (
//     [0] => apple
//     [1] => banana
//     [3] => grape
//     [4] => kiwi
// )

// Re-index the array
$reIndexedItems = array_values($items);

print_r($reIndexedItems);
/* Expected Output after re-indexing:
Array
(
    [0] => apple
    [1] => banana
    [2] => grape
    [3] => kiwi
)
*/

// Example with array_filter and then re-indexing
$numbers = [1, 2, 3, 4, 5, 6];
$evenNumbers = array_filter($numbers, fn($n) => $n % 2 === 0);
print_r($evenNumbers);
// Output: Array ( [1] => 2 [3] => 4 [5] => 6 )

$reIndexedEvenNumbers = array_values($evenNumbers);
print_r($reIndexedEvenNumbers);
/* Expected Output:
Array
(
    [0] => 2
    [1] => 4
    [2] => 6
)
*/
How it works: When elements are removed from a numerically indexed array (e.g., using `unset()` or `array_filter()`), the original keys are preserved, leading to gaps in the sequence. This can cause issues when iterating with `for` loops or when encoding the array to JSON, as it might become an object instead of an array in JavaScript. The `array_values()` function solves this by returning a new array containing all the values from the input array, but with keys re-indexed numerically starting from 0, ensuring a contiguous sequence.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs