PHP 8 reference · Array Functions

PHP array_reverse() Function

Return a new array with the elements in reverse order. String keys are kept; numeric keys are renumbered by default.

PHP 8 Since 4.0

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

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

Parameters

ParameterDescription
array The input array.
preserve_keys optional true keeps numeric keys too. Default: false

Return value

The reversed array.

Examples

Reverse a listTry it yourself
<?php
print_r(array_reverse([1, 2, 3]));

Output

Array
(
    [0] => 3
    [1] => 2
    [2] => 1
)
KeysTry it yourself
<?php
$ranked = ["gold" => "Ada", "silver" => "Alan"];
print_r(array_reverse($ranked));
print_r(array_reverse(["x", "y"], true));

Output

Array
(
    [silver] => Alan
    [gold] => Ada
)
Array
(
    [1] => y
    [0] => x
)

Version history

VersionChange
PHP 4.0Added

In other languages

Was this page helpful?