PHP

Re-indexing an Array After Removing Elements

Discover how to re-index a PHP array with sequential numeric keys after removing elements, preventing gaps and ensuring consistent indexing.

<?php

$fruits = ['apple', 'banana', 'orange', 'grape', 'kiwi'];

echo "Original array:
";
print_r($fruits);

// Remove 'orange' (key 2)
unset($fruits[2]);

echo "
Array after unset (keys are preserved):
";
print_r($fruits);

// Re-index the array
$reindexedFruits = array_values($fruits);

echo "
Array after re-indexing:
";
print_r($reindexedFruits);
How it works: When elements are removed from a numerically indexed array using `unset()`, their original keys are preserved, leading to gaps in the index sequence. This snippet demonstrates how to fix this using `array_values()`. This function takes an array and returns a new numerically indexed array containing all the values from the input array, effectively re-indexing it from scratch starting at 0. This ensures a clean and consistent array structure.

Need help integrating this into your project?

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

Hire DigitalCodeLabs