PHP
Re-index a Numeric PHP Array After Element Removal
Learn how to properly remove elements from a PHP array and then re-index it to ensure sequential numeric keys, preventing gaps in the array.
<?php
$items = ['apple', 'banana', 'orange', 'grape', 'kiwi'];
// Remove an element by its key
unset($items[1]); // Removes 'banana'
// $items is now ['apple', 2 => 'orange', 3 => 'grape', 4 => 'kiwi']
// Notice the key '1' is missing, and subsequent keys are not re-indexed.
// To re-index the array to have sequential numeric keys:
$reIndexedItems = array_values($items);
// $reIndexedItems is now ['apple', 'orange', 'grape', 'kiwi']
// Keys are 0, 1, 2, 3
// This is also useful after array_filter for conditional removal
$products = ['milk', 'bread', 'eggs', 'yogurt', 'butter'];
$filteredProducts = array_filter($products, function($product) {
return $product !== 'eggs' && $product !== 'yogurt';
});
// $filteredProducts is ['milk', 1 => 'bread', 4 => 'butter'] (original keys preserved)
$reIndexedFilteredProducts = array_values($filteredProducts);
// $reIndexedFilteredProducts is ['milk', 'bread', 'butter'] (new sequential keys)
?>
How it works: When you remove an element from an array using `unset()`, PHP removes the key-value pair but does not automatically re-index the numeric keys, potentially leaving gaps. To create a new array with sequential numeric keys (0, 1, 2, ...), you can use `array_values()`. This function effectively extracts all values from the input array and re-indexes them numerically, making it ideal after `unset()` or `array_filter()`.