How to reverse an associative array in PHP?

This is frequently asked in PHP Interviews to reverse an Associative Array in PHP. The easiest solution is using the inbuilt array_reverse() function. It returns an array with elements in reverse order. The array_reverse() format is


array_reverse ( array $array [, bool $preserve_keys = FALSE ] ) : array

The first argument is an input array and the second is to preserve keys when set to true. (The default value is false). In below example, we will reverse an associative using array_reverse() with and without preserving the keys. The demo is available on Coding ground.

  • First using the array_reverse() function without preserving keys:
/* Create an Associate 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 )

As you can see the keys are not preserved. The value at key 0 changed from ‘Vinay Gulati’ to ‘Canada’.

  • Second is using the array_reverse() function with preserving 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 )
As you can see the keys are preserved. The value at key 0 which is ‘Vinay Gulati’ remains the same.
Important Note
preserved_keys only works for numeric keys. Non-numeric keys are always preserved as it’s default to TRUE.

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.