PHP array_reverse() function with example

array_reverse() work is utilized to restores an array in reverse request, it acknowledges an array and returns another array with values in reverse request.

Syntax

  array_reverse(array, [preserve]);

Example:

  Input:
    $arr1 = array(10, 20, 30, 40, 50);

    Output:
    Array
    (
        [0] => 50
        [1] => 40
        [2] => 30
        [3] => 20
        [4] => 10
    )

PHP code 1:

<?php
    $arr1 = array(10, 20, 30, 40, 50);
    $arr2 = array("name" => "Amit", "age" => 21, "gender" => "Male");
    
    //printing array in reverse order
    print_r (array_reverse($arr1));
    print_r (array_reverse($arr2));
?>

Output

Array
(
    [0] => 50
    [1] => 40
    [2] => 30
    [3] => 20
    [4] => 10
)
Array
(
    [gender] => Male
    [age] => 21
    [name] => Amit
)

PHP code 2:

<?php
    $arr = array(10, 20, 30, 40, 50);
    
    //printing array in reverse order
    print_r (array_reverse($arr));
    print_r (array_reverse($arr, true));
?>

Output

Array
(    
    [0] => 50
    [1] => 40
    [2] => 30
    [3] => 20
    [4] => 10
)    
Array
(    
    [4] => 50
    [3] => 40
    [2] => 30
    [1] => 20
    [0] => 10
) 

Leave a Comment

error: Alert: Content is protected!!