How to reverse an array preserving keys in PHP?

This is frequently asked in PHP Interviews to reverse an Array preserving keys in PHP. The easy solution is using the inbuilt array_reverse() function. In the below example, we will reverse an associative using array_reverse() preserving keys and without preserving keys. Also a demo on coding ground is available.

  • First using the array_reverse() without preserving the keys:
/* Create an Array */
         $clientInfo = array("Vinay Gulati", "Toronto", "Canada");

/* Print an Array */
         print "Original Array is: ";
         print_r($clientInfo);

/* Reverse an array without preserving keys */
         print "Reversed Array is: ";
         print_r(array_reverse($clientInfo));
Output
Original Array is: Array
(
[0] => Vinay Gulati
[1] => Toronto
[2] => Canada
)
Reversed Array is: Array
(
[0] => Canada
[1] => Toronto
[2] => Vinay Gulati
)
  • Second using the array_reverse() and preserving the keys:
/* Create an Associate Array */
$clientInfo = array("Vinay Gulati", "Toronto", "Canada");

/* Print an Array */
print "Original Array is: ";
print_r($clientInfo);

/* Reverse an array and preserve keys */
print "Reversed Array with keys preserved is: ";
print_r(array_reverse($clientInfo, true));
Output
Original Array is: Array
(
[0] => Vinay Gulati
[1] => Toronto
[2] => Canada
)
Reversed Array with keys preserved is: Array
(
[2] => Canada
[1] => Toronto
[0] => Vinay Gulati
)

One comment

Leave a Reply