Home » PHP

PHP array_reverse() function with example

PHP array_reverse() function: Here, we are going to learn about the array_reverse() function with example in PHP.
Submitted by IncludeHelp, on February 22, 2019

PHP array_reverse() function

array_reverse() function is used to returns an array in reverse order, it accepts an array and returns a new array with values in reverse order.

Syntax:

    array_reverse(array, [preserve]);

Here,

  • array is an array.
  • preserve is an optional parameter and its default value is false, it is used to define whether we want to preserve the keys or not. If it sets to true – keys will also be reversed.

Examples:

    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
) 





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.