0
0
PhpHow-ToBeginner · 3 min read

How to Use array_reverse in PHP: Syntax and Examples

In PHP, use array_reverse to reverse the order of elements in an array. It takes the array as input and returns a new array with elements in reverse order, optionally preserving keys with a second parameter.
📐

Syntax

The array_reverse function has this syntax:

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

$array is the input array to reverse.

$preserve_keys is optional. If true, the original keys are kept; otherwise, keys are reset to numeric indexes.

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

Example

This example shows how to reverse a simple array and how to preserve keys.

php
<?php
$fruits = ['apple', 'banana', 'cherry'];
$reversed = array_reverse($fruits);
$reversed_with_keys = array_reverse($fruits, true);

print_r($reversed);
print_r($reversed_with_keys);
?>
Output
Array ( [0] => cherry [1] => banana [2] => apple ) Array ( [2] => cherry [1] => banana [0] => apple )
⚠️

Common Pitfalls

One common mistake is expecting array_reverse to change the original array. It returns a new reversed array instead.

Another is forgetting the $preserve_keys parameter when you want to keep keys, which can cause unexpected numeric keys.

php
<?php
// Wrong: expecting original array to change
$numbers = [1, 2, 3];
array_reverse($numbers);
print_r($numbers); // Still [1, 2, 3]

// Right: assign the reversed array
$reversed = array_reverse($numbers);
print_r($reversed); // [3, 2, 1]

// Wrong: keys reset when you want to keep them
$assoc = ['a' => 1, 'b' => 2];
$rev = array_reverse($assoc);
print_r($rev); // keys are 0 and 1

// Right: preserve keys
$rev_preserved = array_reverse($assoc, true);
print_r($rev_preserved); // keys 'b' and 'a'
?>
Output
Array ( [0] => 1 [1] => 2 [2] => 3 ) Array ( [0] => 3 [1] => 2 [2] => 1 ) Array ( [0] => 2 [1] => 1 ) Array ( [b] => 2 [a] => 1 )
📊

Quick Reference

ParameterDescriptionDefault
$arrayThe input array to reverseRequired
$preserve_keysWhether to keep original keys (true or false)false

Key Takeaways

Use array_reverse to get a new array with elements in reverse order.
Set the second parameter to true to preserve original keys.
array_reverse does not modify the original array; it returns a new one.
Without preserving keys, numeric keys are reset starting from zero.