PHP array reverse

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

PHP: array_reverse() function

PHP: Create an array with elements in reverse order

The array_reverse() function is used to reverse the order of the elements in an array.

Version

(PHP 4 and above)

Syntax

array_reverse(array_name, preserve_keys) 

Parameter

Name

Description

Required /
Optional

Type

array_name

Specifies the name of the array.

Required

Array

preserve_keys

Specify TRUE or FALSE whether function shall preserve the array's keys or not. The default value is FALSE.

Optional

Boolean

Return value

The reversed array.

Value Type : Array

Pictorial Presentation :

php array array_reverse() function

Example :

  1. $a= array(1,2,3,4,5);  

  2. $x = array_reverse($a,true);  

  3. $y = array_reverse($a);  

  4. print_r($x);  

  5. echo '
     ';  

  6. print_r($y);  

  7. ?>  

Output :

Array ( [4] => 5 [3] => 4 [2] => 3 [1] => 2 [0] => 1 )
Array ( [0] => 5 [1] => 4 [2] => 3 [3] => 2 [4] => 1 )