PHP
Re-indexing Numeric Arrays After Modification
Learn how to reset and re-index the numeric keys of an array in PHP, which is common after operations like filtering or removing elements, using `array_values()`.
<?php
$originalArray = ['apple', 'banana', 'orange', 'grape', 'kiwi'];
// Simulate removing an element, leaving a gap in keys
unset($originalArray[1]); // Remove 'banana'
unset($originalArray[3]); // Remove 'grape'
echo "Array with gaps: " . print_r($originalArray, true) . "
";
// Expected: ['apple', 2 => 'orange', 4 => 'kiwi'] - keys are 0, 2, 4
// Re-index the array using array_values()
$reindexedArray = array_values($originalArray);
echo "Re-indexed Array: " . print_r($reindexedArray, true) . "
";
// Expected: ['apple', 'orange', 'kiwi'] - keys are 0, 1, 2
// Example with filtering, also creating non-sequential keys
$numbers = [1, 2, 3, 4, 5, 6];
$evenNumbers = array_filter($numbers, function($num) {
return $num % 2 === 0;
});
echo "Filtered even numbers (with original keys): " . print_r($evenNumbers, true) . "
";
// Expected: [1 => 2, 3 => 4, 5 => 6]
$reindexedEvenNumbers = array_values($evenNumbers);
echo "Re-indexed even numbers: " . print_r($reindexedEvenNumbers, true) . "
";
// Expected: [2, 4, 6]
?>
How it works: When elements are removed from an array (e.g., using `unset`) or an array is filtered, the numeric keys often become non-sequential, creating 'gaps.' The `array_values()` function is a simple yet powerful way to extract all values from an array and return them in a new, numerically indexed array starting from `0`. This is essential for maintaining consistent array structures and ensuring correct iteration or indexing in subsequent operations.