PHP

Re-index a PHP Array After Deleting Elements

Learn how to reset and re-index the numeric keys of a PHP array after elements have been removed, ensuring a contiguous sequence starting from zero.

<?php
$data = ['apple', 'banana', 'cherry', 'date', 'elderberry'];

// Remove some elements
unset($data[1]); // banana
unset($data[3]); // date

echo "Array with gaps:
";
print_r($data);

// Re-index the array
$reindexedData = array_values($data);

echo "
Re-indexed array:
";
print_r($reindexedData);

// Example with filtering and re-indexing
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
$filteredNumbers = array_filter($numbers, fn($num) => $num % 2 === 0);

echo "
Filtered array (keys preserved):
";
print_r($filteredNumbers);

$reindexedFilteredNumbers = array_values($filteredNumbers);

echo "
Filtered and re-indexed array:
";
print_r($reindexedFilteredNumbers);
?>
How it works: When elements are removed from a numerically indexed array using `unset` or filtered using functions like `array_filter`, the original keys are preserved, which can create gaps and non-sequential indices. `array_values()` is a simple yet powerful function that extracts all values from an array and returns a new numerically indexed array, effectively re-indexing it with keys starting from 0, without any gaps.

Need help integrating this into your project?

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

Hire DigitalCodeLabs