PHP

Re-index PHP Array After Element Removal

Understand how to reset and re-sequence numeric keys in a PHP array after elements have been removed using `unset`, ensuring sequential indexing starting from zero.

$items = ['apple', 'banana', 'cherry', 'date', 'elderberry'];

// Remove 'cherry' (index 2) and 'elderberry' (index 4)
unset($items[2]);
unset($items[4]);

echo "Array after unset (keys are not sequential):
";
print_r($items);
// Output: Array ( [0] => apple [1] => banana [3] => date )

// Re-index the array to make keys sequential again
$reindexedItems = array_values($items);

echo "Array after re-indexing:
";
print_r($reindexedItems);
// Output: Array ( [0] => apple [1] => banana [2] => date )
How it works: When you remove elements from a numerically indexed PHP array using `unset()`, the remaining keys stay as they were, potentially creating gaps in the numeric sequence. This snippet demonstrates how to re-index the array using `array_values()`. `array_values()` extracts all the values from an array and returns them in a new numerically indexed array, with keys starting from 0 and continuing sequentially, effectively 'resetting' the indexing.

Need help integrating this into your project?

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

Hire DigitalCodeLabs