PHP
Re-index a PHP Array After Removing Elements
Learn how to easily re-index a numerically indexed PHP array after using `unset()` to remove elements, ensuring sequential integer keys.
<?php
$fruits = ["apple", "banana", "cherry", "date"];
echo "Original array:
";
print_r($fruits);
// Remove an element
unset($fruits[1]); // Removes "banana"
echo "Array after unset():
";
print_r($fruits); // Notice the missing index 1
// Re-index the array
$reindexedFruits = array_values($fruits);
echo "Array after re-indexing with array_values():
";
print_r($reindexedFruits);
// Example with associative array (array_values still extracts values but loses keys)
$associativeItems = [
"first" => "laptop",
"second" => "mouse",
"third" => "keyboard"
];
unset($associativeItems["second"]);
$reindexedAssociative = array_values($associativeItems); // Becomes numerically indexed
echo "Associative array after unset and then array_values:
";
print_r($reindexedAssociative);
?>
How it works: When you remove elements from a numerically indexed array using `unset()`, the numerical keys are not automatically re-ordered, which can lead to gaps in indices. The `array_values()` function returns all values from an array, creating a new numerically indexed array starting from 0, effectively re-indexing it. For associative arrays, `array_values()` extracts the values into a new numerically indexed array, discarding the original string keys.