PHP

Re-index Numerical Array After Deleting Elements

Learn how to easily re-index a numerically indexed PHP array to have sequential, zero-based keys after elements have been removed, preventing unexpected array behavior.

<?php
$items = ['apple', 'banana', 'orange', 'grape'];
unset($items[1]); // Remove 'banana'
unset($items[3]); // Remove 'grape'

// At this point, $items is ['apple', 2 => 'orange']
echo "Before re-indexing:
";
print_r($items);

$reindexedItems = array_values($items);

echo "
After re-indexing:
";
print_r($reindexedItems);

/*
Expected Output:
Before re-indexing:
Array
(
    [0] => apple
    [2] => orange
)

After re-indexing:
Array
(
    [0] => apple
    [1] => orange
)
*/
?>
How it works: When elements are removed from a numerically indexed array using `unset()`, the original keys are preserved, leading to non-sequential indices. The `array_values()` function is a simple and effective way to reset the array's keys, making them sequential and starting from zero. This is crucial for loops and functions that expect consistently indexed arrays.

Need help integrating this into your project?

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

Hire DigitalCodeLabs