Thursday, September 4, 2025
HomeLanguagesPHP array_reverse() Function

PHP array_reverse() Function

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

RELATED ARTICLES

Most Popular

Dominic
32260 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6625 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11855 POSTS0 COMMENTS
Shaida Kate Naidoo
6747 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6694 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS