Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to reverse an array

Short answer

array_reverse() returns the array in reverse order:

<?php
 
echo implode(', ', array_reverse(['first', 'second', 'third']));

Output:

third, second, first

Preserving keys

Numeric keys are renumbered by default. A second argument of true keeps them:

<?php
 
$items = [10 => 'a', 20 => 'b'];
 
echo json_encode(array_reverse($items)), ' ', json_encode(array_reverse($items, true));

Output:

["b","a"] {"20":"b","10":"a"}

This is not sorting

array_reverse() flips the order, while rsort() arranges the values in descending order:

<?php
 
$numbers = [3, 9, 1];
 
echo implode(', ', array_reverse($numbers)), ' | ';
 
rsort($numbers);
echo implode(', ', $numbers);

Output:

1, 9, 3 | 9, 3, 1

Functions used in this recipe

  • array_reverse — Returns an array with its elements in reverse order.
  • rsort — Sorts an array in descending order.
  • krsort — Sorts an array by keys in descending order.

Thanks for reading!

Donate to the site — we work hard for you.