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
array_reverse( array, preserve )
where
| Parameter | Description |
|---|---|
| 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
<?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.
