PHP Array array_reverse() Function (With Examples)

In this tutorial, we will learn about the PHP array_reverse() function with its usage, syntax, parameters, return value, and examples. By IncludeHelp Last updated : December 31, 2023

PHP array_reverse() function

The 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

The syntax of the array_reverse() function:

array_reverse(array, [preserve]);

Parameters

The parameters of the array_reverse() function:

  • 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.

Return Value

The return type of this method is array, it returns the reversed array.

Sample Input/Output

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

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

PHP array_reverse() Function Example 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

The output of the above example is:

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

PHP array_reverse() Function Example 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

The output of the above example is:

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

To understand the above examples, you should have the basic knowledge of the following PHP topics:

All PHP Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.