Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

array_reverse

Returns an array with its elements in reverse order.

Available since: PHP 4

Syntax

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

Parameters

ParameterTypeDescription
$arrayarrayThe source array.
$preserve_keysboolIf `true`, numeric keys are preserved. String keys are always preserved.

Return value

arrayA new array in reverse order.

Examples

A list in reverse order:

<?php
 
echo implode(', ', array_reverse([1, 2, 3]));

Output:

3, 2, 1

String keys stay with their values:

<?php
 
print_r(array_reverse(['a' => 1, 'b' => 2]));

Output:

Array
(
    [b] => 2
    [a] => 1
)

Notes

The source array is not modified. To reverse a string rather than an array, use strrev().

See also

  • sort — Sorts an array in ascending order.
  • array_slice — Returns part of an array.

Related recipes

In the tutorial

  • Arrays — Lists and associative arrays in PHP — creating, changing, iterating and useful functions.

Thanks for reading!

Donate to the site — we work hard for you.