In this tutorial, you shall learn how to reverse an array in PHP using array_reverse() function, with syntax and examples.

PHP Reverse Array

To reverse an array in PHP, we can use array_reverse() function.

The PHP array_reverse() function returns a new array with elements of the original array in reverse order.

In this tutorial, we will learn how to use array_reverse() function to reverse the order of elements in given array.

Syntax

The syntax of array_reverse() function is

</>
Copy
array_reverse( array, preserve )

where

ParameterDescription
array[mandatory] The source array for reversing.
preserve[optional] Boolean value telling if the function should preserve the keys of the indexed array or not. This parameter has no effect on associative arrays.

Function Return Value

array_reverse() returns the a new array with elements of the source array arranged in reverse order. Original array/ Source array remains unchanged.

Examples

1. Reverse an Indexed Array

In this example, we will take an indexed array of items, and reverse the order of elements using array_reverse() function.

PHP Program

</>
Copy
<?php
  $array1 = array(5=>"apple", "banana", "mango");
  $result = array_reverse($array1);
  print_r($result);
?>

Output

With default value of preserve parameter being FALSE, the indexes for the items are not preserved in the resulting reverse array.

PHP array_reverse() - Reverse an Indexed Array

2. Reverse an Associative Array

In this example, we will take an array of items, say array1, and create a new array with elements of array1 but in reverse order.

PHP Program

</>
Copy
<?php
$array1 = array("a"=>"apple", "b"=>"banana", "m"=>"mango");
$result = array_reverse($array1);
print_r($result);
?>

Output

PHP array_reverse() - Reverse an Array

3. Preserve the original indices while reversing indexed array

In this example, we will try with argument value of TRUE for preserve parameter when calling array_reverse() function.

PHP Program

</>
Copy
<?php
$array1 = array(5=>"apple", "banana", "mango");
$result = array_reverse($array1, TRUE);
print_r($result);
?>

Output

The index of the items in the reversed array should have the indexes from the same array.

PHP array_reverse() - preserve = TRUE for Indexed Arrays

Conclusion

In this PHP Tutorial, we learned how to reverse an array, using PHP Array array_reverse() function.