Tutorialspoint.dev

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 users choice. This function accepts an array as parameter and returns the array with elements in reversed order.

Syntax:

array array_reverse($array, $key_preserve)

Parameters:
The function takes two arguments and 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 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:

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

    <?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: ";
    print_r($array);
      
    echo " After: ";
    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
    )
  2. Let’s see what happens when we pass the key_preserve parameter as TRUE. This preserve the keys.

    <?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: ";
    print_r($array);
      
    echo " After: ";
    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



This article is attributed to GeeksforGeeks.org

You Might Also Like

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter