Categories
PHP

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.

array_reverse

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

<?php
 //Syntax
 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:

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

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:

<?php
 $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)

Working with arrays: