Reorder numeric keys of an array from “0″ onwards

Comments Off
Identi.ca
Share
blackboard
Photo : ArtsieAspie

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 :)

Creative Commons License

This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.

Sources :

Comments are closed.

About The Author

maximem

I'm a french web developer co-managing a little web agency named Wixiweb in the north of France. I have about 6 years of working experience with PHP and I'm a Zend Framework Certified Engineer.

Post Tags