Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Array Functions

PHP array_reverse() function

Reference for PHP array_reverse(): return an array in reverse order, see how string and numeric keys behave, and preserve integer keys when needed.

array_reverse() returns a new array with the elements in the opposite order. The original array is not changed.

String keys always stay attached to their values. Integer keys are renumbered from 0 unless you ask for them to be preserved, which matters if your numeric keys carry meaning such as ids.

PHP
<?php
print_r(array_reverse(["a", "b", "c"])); // c, b, a

Try it

PHP Lists and associative arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Preserving integer keys

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
array_reverse(array $array, bool $preserve_keys = false): array
Name Description
$array The input array.
$preserve_keys If true, integer keys keep their values. Defaults to false, which renumbers them. String keys are always preserved.

Return value: a new array with the elements in reverse order.

Usage notes

  • A copy, not in place. To reverse a variable, assign the result back: $list = array_reverse($list);.
  • Integer keys are renumbered by default, even when mixed with string keys. Use true to keep them.
  • Sorting backwards is not the same thing. rsort() and arsort() order by value; array_reverse() only flips the current order.
  • Iterating backwards over a list without copying is possible with for ($i = count($a) - 1; $i >= 0; $i--), which is useful for very large arrays.
  • Strings: use strrev() for bytes. For multibyte text, split into characters first (for example with mb_str_split()), reverse, and join.
  • Pairing with array_slice(): array_slice(array_reverse($a), 0, 3) gives the last three elements, newest first.