Throughout PHP array_reverse Function Example you will learn How to reverse the order of an array in PHP. We have added reverse array one-dimensional array, associative array and multidimensional array in PHP.
We have also added reverse an array in PHP without using the array_reverce function as well.
PHP Array Reverse Example
The PHP array_reverse() function is in-built PHP function, which is used to reverse the items or elements of the array.
Syntax:
The basic syntax of the array_reverse()
function is given with:
array_reverse(array, preserve)
Parameter Values:
The function accepts two parameters first one is an array and the second one is preserve (TRUE/FALSE)
- Array:- The array parameter is required, and it describes the array.
- preserve:- This is the second parameter of this function and It is an optional parameter. It specifies if the function should preserve the keys of the array or not. Possible values: true, false.
Example 1: Single Dimensional Array Reverse
<?php
$numbers = [5, 10, 15, 20];
$reversed = array_reverse($numbers);
print_r($reversed);
Output:
Array
(
[0] => 20
[1] => 15
[2] => 10
[3] => 5
)
Example 2: Associative Array Reverse
<?php
$arrayData = array("a"=>"php", "b"=>"jquery", "c"=>"laravel");
print_r(array_reverse($arrayData));
?>
Output:
Array (
[c] => laravel
[b] => jquery
[a] => php
)
Example 3: Reverse multidimensional array in PHP
<?php
$array = array(
array("a"=>"PHP","b"=>"JAVA","c"=>".NET"),
array("d"=>"javascript","e"=>"c","f"=>"c#"),
);
$reverseArray = array_reverse($array);
print_r($reverseArray);
?>
Output:
Array
(
[0] => Array ( [d] => javascript [e] => c [f] => c# )
[1] => Array ( [a] => PHP [b] => JAVA [c] => .NET )
)
Example 4: How to reverse an array in PHP without function?
You can use the for loop the and unset() function of PHP to reverse an array without using the function in PHP.
<?php
$arr = ['a','b','c','d','e','f'];
for($i=count($arr)-1;$i>=0;$i--){
$arr[]=$arr[$i];
unset($arr[$i]);
}
print_r($arr);
?>
Output:
Array
(
[6] => f
[7] => e
[8] => d
[9] => c
[10] => b
[11] => a
)
Hope you enjoy with php arrray reverce function example..