The array_reverse Function
The array_reverse
function reverses
an array in reverse order. The first parameter
is the array, and the second is whether to preserve keys
when rearranging elements or not (true
- yes, false
- no). The second parameter is optional.
In this case, by default
the second parameter is false
. String
keys are always preserved, regardless of the value
of this parameter.
Syntax
array_reverse(array $array, bool $preserve_keys = false): array
Example
Let's reverse an array:
<?php
$arr = ['a', 'b', 'c', 'd', 'e'];
$res = array_reverse($arr);
var_dump($res);
?>
Code execution result:
['e', 'd', 'c', 'b', 'a']
Example
Let's reverse an associative array:
<?php
$arr = ['a' => 1, 'b' => 2, 'c' => 3];
$res = array_reverse($arr);
var_dump($res);
?>
Code execution result:
['c' => 3, 'b' => 2, 'a' => 1]
See Also
-
the
strrev
function,
which reverses a string -
the
array_flip
function,
which swaps keys and values