[Previous] [Contents] [Next]


Reordering elements in arrays with array_reverse( )


Often it's useful to consider an array in reverse order. The array_reverse( ) function creates a new array by reversing the elements from a source array:

array array_reverse(array source [, bool preserve_keys])

The following example shows how to reverse an indexed array of strings:

$count = array("zero", "one", "two", "three");

$countdown = array_reverse($count);

Setting the optional preserve_keys argument to true reverses the order but preserves the association between the index and the elements. For a numerically indexed array, this means that the order of the elements is reversed, but the indexes that access the elements don't change. This might seem a bit weird, but the following example shows what is happening:

$count = array("zero", "one", "two", "three");
$countdown = array_reverse($count, true);
print_r($countdown);

This prints:

Array ([3] => three [2] => two [1] => one [0] => zero)


[Previous] [Contents] [Next]