w3resource

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

Example:

<?php
$a= array(1,2,3,4,5);
$x = array_reverse($a,true);
$y = array_reverse($a);
print_r($x);
echo '</br> ';
print_r($y);
?>

Output:

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

Pictorial Presentation:

php function reference: array_reverse() function

View the example in the browser

Practice here online :

See also

PHP Function Reference

Previous: array_reduce
Next: array_search



PHP: Tips of the Day

PHP: Extract numbers from a string

$str = 'In My Cart : 11 12 items';
preg_match_all('!\d+!', $str, $matches);
print_r($matches);