0
0
PhpHow-ToBeginner · 3 min read

How to Reverse an Array in PHP: Simple Guide

To reverse an array in PHP, use the array_reverse() function which returns a new array with elements in reverse order. You can optionally preserve the original keys by passing true as the second argument.
📐

Syntax

The array_reverse() function takes an array as the first argument and an optional boolean as the second argument to preserve keys.

  • array_reverse(array $array, bool $preserve_keys = false): array
  • $array: The input array to reverse.
  • $preserve_keys: If true, original keys are kept; otherwise, keys are reset.
php
<?php
array_reverse(array $array, bool $preserve_keys = false): array;
?>
💻

Example

This example shows how to reverse a simple array and how to reverse it while preserving keys.

php
<?php
$fruits = ['apple', 'banana', 'cherry'];

// Reverse without preserving keys
$reversed = array_reverse($fruits);
print_r($reversed);

// Reverse while preserving keys
$reversed_preserve = array_reverse($fruits, true);
print_r($reversed_preserve);
?>
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 modify the original array. It returns a new reversed array instead. Also, forgetting to set $preserve_keys to true when you want to keep keys can cause unexpected key resets.

php
<?php
$numbers = [10 => 'ten', 20 => 'twenty', 30 => 'thirty'];

// Wrong: expecting original array to change
array_reverse($numbers);
print_r($numbers); // Original array unchanged

// Right: assign reversed array
$reversed = array_reverse($numbers);
print_r($reversed); // Keys reset

// Right: preserve keys
$reversed_preserve = array_reverse($numbers, true);
print_r($reversed_preserve); // Keys preserved
?>
Output
Array ( [10] => ten [20] => twenty [30] => thirty ) Array ( [0] => thirty [1] => twenty [2] => ten ) Array ( [30] => thirty [20] => twenty [10] => ten )
📊

Quick Reference

FunctionDescriptionExample
array_reverse()Returns a new array with elements reversedarray_reverse([1,2,3]) => [3,2,1]
array_reverse() with preserve keysReverses array and keeps original keysarray_reverse(['a'=>1,'b'=>2], true) => ['b'=>2,'a'=>1]

Key Takeaways

Use array_reverse() to get a reversed copy of an array in PHP.
Pass true as second argument to preserve original keys when reversing.
array_reverse() does not change the original array; it returns a new one.
Always assign the result of array_reverse() to a variable to use the reversed array.