Reordering Array Keys After Unsetting Elements
When unsetting elements from an array, the array keys may become disjointed, affecting the index order. To resolve this, you can use the array_values() method.
Consider the following code:
<code class="php">$array = array(1, 2, 3, 4, 5); foreach ($array as $i => $info) { if ($info == 1 || $info == 2) { unset($array[$i]); } } print_r($array); // Outputs: [3, 4, 5] (disjointed keys)</code>
To reassign keys, use array_values():
<code class="php">$array = array_values($array); print_r($array); // Outputs: [0 => 3, 1 => 4, 2 => 5] (reordered keys)</code>
array_values() creates a new array with values preserved and keys starting from zero index, effectively reordering the array keys.
The above is the detailed content of How to Reorder Array Keys After Unsetting Elements?. For more information, please follow other related articles on the PHP Chinese website!