How to Reorder Array Elements from Last to First in PHP
  John Mwaniki /   05 Dec 2023

How to Reorder Array Elements from Last to First in PHP

While array elements typically follow a sequential order, there may come scenarios where reordering elements becomes necessary. One such is reversing the order of array elements, placing the last element at the beginning and the first at the end.

For instance, the most recent entries would be considered more important when dealing with an array of time-sensitive data, such as timestamps or transaction logs. You would therefore want to have them at the beginning of the array and the oldest at the end.

Reversing the order of array elements to start with the latest entry makes accessing and processing the relevant information easier without traversing the entire array.

Reversing Array Order in PHP

You can easily achieve this using the array_reverse() function. This is a built-in function in PHP, which as its name suggests, reverses the order of elements in an array, effectively transforming it from last to first.

Syntax

array_reverse(array)

This function takes an array as the parameter and returns a new array with the elements reversed.

Example

// Sample Array
$data = array("Avocado", "Banana", "Watermelon", "Mango");

// Reversing Array Elements
$reversedData = array_reverse($data);

echo "Original Array:<br>";
print_r($data);

echo "<br>Reversed Array:<br>";
print_r($reversedData);

Output:
Original Array:
Array ( [0] => Avocado [1] => Banana [2] => Watermelon [3] => Mango )
Reversed Array:
Array ( [0] => Mango [1] => Watermelon [2] => Banana [3] => Avocado )

In this example, the original array $data contains four elements. The array_reverse() function is then applied to $data, producing a new array, $reversedData, where the elements are now in reverse order.

If you want to preserve the elements' keys when reversing the array, then you will need to use an optional second parameter true.

// Sample Array
$data = array("Avocado", "Banana", "Watermelon", "Mango");

// Reversing Array Elements
$reversedData = array_reverse($data, true);

echo "Original Array:<br>";
print_r($data);

echo "<br>Reversed Array:<br>";
print_r($reversedData);

Output:
Original Array:
Array ( [0] => Avocado [1] => Banana [2] => Watermelon [3] => Mango )
Reversed Array:
Array ( [3] => Mango [2] => Watermelon [1] => Banana [0] => Avocado )

In this example, the array keys are preserved, offering a different perspective on the reordered data.

That's it!

Now you know how to reverse the order of elements in a PHP array.