PHP Function Reference

PHP array_reverse() Function



The PHP array_reverse() function takes an input array and returns a new array with the order of the elements reversed.

Syntax

array_reverse(array, preserve_keys)

Parameters

array Required. Specify the input array.
preserve_keys Optional. If set to true numeric keys are preserved. Non-numeric keys are not affected by this setting and will always be preserved. Default is false.

Return Value

Returns the reversed array.

Exceptions

NA.

Example:

The example below shows the usage of array_reverse() function.

<?php
$Arr = array(10, 20, "Hello", "World");

//reversing the array
$reversed = array_reverse($Arr);

//reversing the array with 
//preserving the keys
$preserved  = array_reverse($Arr, true);

print_r($Arr);
echo "\n";
print_r($reversed);
echo "\n";
print_r($preserved);
?>

The output of the above code will be:

Array
(
    [0] => 10
    [1] => 20
    [2] => Hello
    [3] => World
)

Array
(
    [0] => World
    [1] => Hello
    [2] => 20
    [3] => 10
)

Array
(
    [3] => World
    [2] => Hello
    [1] => 20
    [0] => 10
)

Example:

Consider one more example where the array_reverse() function is used with an associative array.

<?php
$Arr = array(10=>"Red",
             20=>"Green",
             30=>"Blue");

//reversing the array
$reversed = array_reverse($Arr);

//reversing the array with 
//preserving the keys
$preserved  = array_reverse($Arr, true);

print_r($Arr);
echo "\n";
print_r($reversed);
echo "\n";
print_r($preserved);
?>

The output of the above code will be:

Array
(
    [10] => Red
    [20] => Green
    [30] => Blue
)

Array
(
    [0] => Blue
    [1] => Green
    [2] => Red
)

Array
(
    [30] => Blue
    [20] => Green
    [10] => Red
)

❮ PHP Array Reference