The array_reverse
method reverses an array and returns the reversed array as a new array.
array_reverse(array $array_to_reverse, bool $preserve_keys = false): array
array_to_reverse
: The array to be reversed.
preserve_keys
: An optional Boolean value. If we set the value of preserve_keys
as true
, then numeric keys are preserved for the array values. Non-numeric keys will always be preserved. The default value is false
.
<?php$arr = array(1 => 1, 3 => 3, 'two' => 2);print_r(array_reverse($arr))?>
In the code above, we create an array with the following values.
1 => 1,
3 => 3,
'two' => 2
We call the array_reverse
method on the created array. This will reverse the order of the array. When the array is reversed, the non-numeric keys are not changed, whereas the numeric keys are changed.
To preserve the numeric keys, we can pass true
for the preserve_keys
argument.
<?php$arr = array(1 => 1, 3 => 3, 'two' => 2);print_r(array_reverse($arr, true))?>
In the code above, we create an array with the following values.
1 => 1,
3 => 3,
'two' => 2
We call the array_reverse
method with the preserve_keys
argument as true
.
array_reverse($arr, true)
This will not change the numeric keys of the values.