Reorder numeric keys of an array from “0″ onwards
Back in the game with another PHP quick tip
Ever faced the problem of needing to loop through an array but it has non-consecutive numeric keys ?
There are some easy ways to reassign array keys from 0 onwards.
Supposing that I have an array with numeric keys as below :
$array = array(
'zero',
'one',
'two',
'three',
'four',
'five'
);
print_r($array);
/*
Output :
Array
(
[0] => zero
[1] => one
[2] => two
[3] => three
[4] => four
[5] => five
)
*/
For some reasons I unset one of the array elements :
unset($array[2]);
print_r($array);
/*
Output :
Array
(
[0] => zero
[1] => one
[3] => three
[4] => four
[5] => five
)
*/
Keys ordering is now broken.
But it’s really simple to reorder them. No need to do kind of tricky foreach() loop, just use array_values() PHP built-in function :
$array = array_values($array);
print_r($array);
/*
Output :
Array
(
[0] => zero
[1] => one
[2] => three
[3] => four
[4] => five
)
*/
Ta-da
To go a little further, the first or last element of an array can be removed without breaking keys order.
It can be done very easily by using array_shift() and array_pop() functions :
$array = array(
'zero',
'one',
'two',
'three',
'four',
'five'
);
print_r($array);
/*
Array
(
[0] => zero
[1] => one
[2] => two
[3] => three
[4] => four
[5] => five
)
*/
array_shift($array);
print_r($array);
/*
Array
(
[0] => one
[1] => two
[2] => three
[3] => four
[4] => five
)
*/
array_pop($array);
print_r($array);
/*
Array
(
[0] => one
[1] => two
[2] => three
[3] => four
)
*/
Hope it helps
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.