Reordering array elements 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.


This function accepts an array as a source and returns an array with elements in reverse order.

 array_reverse(array $array, bool $preserve_keys = false): array

array_reverse accepts two parameters:

  1. array as source
  2. preserve_keys Set TRUE or FALSE, if set to TRUE numeric keys are preserved.

array_reverse examples

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

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

This prints:

//$count result
Array ([0] => zero [1] => one [2] => two [3] => three)

//$countdown result
Array ([0] => three [1] => two [2] => one [3] => zero)

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

This prints:

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

Working with arrays: