Home >Backend Development >PHP Tutorial >How to Rebase Array Keys After Unsetting Elements?
Rebase Array Keys After Unsetting Elements
When elements are removed from an array, its keys can become disjointed. This can be undesired, especially when maintaining proper indexing is important.
To rebase array keys after unsetting elements, you can use the array_values() function.
Consider the following array:
$array = array(1, 2, 3, 4, 5);
If we unset certain keys using a foreach loop:
foreach ($array as $i => $info) { if ($info == 1 || $info == 2) { unset($array[$i]); } }
This would result in a disjointed array:
array(3) { [2] => int(3) [3] => int(4) [4] => int(5) }
To rebase the array keys, simply use array_values():
$array = array_values($array);
This function returns a new array with sequentially rebased keys:
array(3) { [0] => int(3) [1] => int(4) [2] => int(5) }
The above is the detailed content of How to Rebase Array Keys After Unsetting Elements?. For more information, please follow other related articles on the PHP Chinese website!