Reverse Array In PHP | PHP array_reverse Function

Reverse array in PHP; Through this tutorial, i am going to show you how to reverse array one-dimensional array, associative array and multidimensional array in PHP.

How To Reverse Array In PHP

Using the PHP array_reverse() function, you can reverse the items or elements of the array in PHP.

Syntax of array_reverse:

The syntax of array_reverse() function is following.

array_reverse(array, preserve)

Parameters Of array reverse function:

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 – Reverse One Dimensional Array Element In PHP

Let’s take an example using array_reverse function to reverse one dimensional or single dimensional array elements in PHP; is as follows:

<?php
  
  $numericArray = array(5, 12, 18, 50, 49);
  $resNumericArray = array_reverse($numericArray);
  print_r($resNumericArray);
?>

The output of the above givne PHP code; is as follows:

Array
(
    [0] => 49
    [1] => 50
    [2] => 18
    [3] => 12
    [4] => 5
)

Example 2 – Reverse Associative Array Elements In PHP

Let’s take an associative array with array_reverse function to reverse elements of associative array in PHP; is as follows:

<?php
  
  $keyValueArray = array("a"=>"PHP","b"=>"JAVA","c"=>".NET");
  $resKeyValueArray = array_reverse($keyValueArray);
  print_r($resKeyValueArray);
?>

The output of the above php code; is as follows:

Array 
( 
	[c] => .NET 
	[b] => JAVA 
	[a] => PHP 
)

Example 3 – PHP reverse multidimensional array

Let’s take a new example with the multidimensional array to reverse array elements in PHP; is as follows:

<?php
  
$array = array(
         array("a"=>"PHP","b"=>"JAVA","c"=>".NET"),
         array("d"=>"javascript","e"=>"c","f"=>"c#"),
);
  $reverseArray = array_reverse($array);
  print_r($reverseArray);
?> 

The output of the above php code; is as follows:

Array 
( 
 [0] => Array ( [d] => javascript [e] => c [f] => c# ) 
 [1] => Array ( [a] => PHP [b] => JAVA [c] => .NET ) 
)

Recommended PHP Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published.