Open In App

PHP array_reverse() Function

Last Updated : 10 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

This inbuilt function of PHP is used to reverse the elements of an array including the nested arrays. Also, we have an option of preserving the key elements according to the user’s choice. This function accepts an array as a parameter and returns the array with elements in reversed order. 

Syntax:

array array_reverse($array, $key_preserve)

Parameters: The function takes two arguments which are described below:

  1. $array (mandatory): This parameter refers to the original array.
  2. $key_preserve (optional): This is an optional parameter and can be set to TRUE or FALSE, it refers to the preservation of keys of the array. By default, the value of this parameter is taken as FALSE.

Return Value: This function returns the array passed in a parameter with elements in reversed order. 

Examples:

Input : $array = (2, 4, 5, 10, 100)
Output : 
Array
(
    [0] => 100
    [1] => 10
    [2] => 5
    [3] => 4
    [4] => 2
)

Input :
Array
(
    [0] => ram
    [1] => aakash
    [2] => saran
    [3] => mohan
)
Output :
Array
(
    [3] => mohan
    [2] => saran
    [1] => aakash
    [0] => ram
)

Below programs illustrate the array_reverse() function in PHP:

This program reverses an array taking the $key_preserve as FALSE by default. This don’t preserve the keys. 

PHP




<?php
 
// PHP function to illustrate the use of array_reverse()
function Reverse($array)
{
    return(array_reverse($array));
}
 
$array = array("ram", "aakash", "saran", "mohan");
 
echo "Before:\n";
print_r($array);
 
echo "\nAfter:\n";
print_r(Reverse($array));
 
?>


Output:

Before:
Array
(
    [0] => ram
    [1] => aakash
    [2] => saran
    [3] => mohan
)

After:
Array
(
    [0] => mohan
    [1] => saran
    [2] => aakash
    [3] => ram
)

Let’s see what happens when we pass the key_preserve parameter as TRUE. This preserve the keys. 

PHP




<?php
 
// PHP function to illustrate the use of array_reverse()
function Reverse($array)
{
    return(array_reverse($array, true));
}
 
$array = array("ram", "aakash", "saran", "mohan");
 
echo "Before:\n";
print_r($array);
 
echo "\nAfter:\n";
print_r(Reverse($array));
 
?>


Output:

Before:
Array
(
    [0] => ram
    [1] => aakash
    [2] => saran
    [3] => mohan
)

After:
Array
(
    [3] => mohan
    [2] => saran
    [1] => aakash
    [0] => ram
)

Reference: http://php.net/manual/en/function.array-reverse.php



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads