This is frequently asked in PHP Interviews to reverse an Associative Array in PHP. The easy solution is using the inbuilt array_reverse() function. But to reverse an associative array without using an inbuilt function is a real challenge. In below example, we will reverse an associative using array_reverse() and without using any inbuilt functions. Also a demo on coding ground is available.
- First using the array_reverse() function:
[code lang=”php”]
/* Create an Associate Array */
$clientInfo = array("name" => "Vinay Gulati", "city" => "Toronto", "country" => "Canada");
/* Print an Array */
print "Original Array is: ";
print_r($clientInfo);
/* Reverse an array using PHP funciton */
print "Reversed Array is: ";
print_r(array_reverse($clientInfo));
[/code]
Original Array is: Array ( [name] => Vinay Gulati [city] => Toronto [country] => Canada )
Reversed Array is: Array ( [country] => Canada [city] => Toronto [name] => Vinay Gulati )
- Second is without using any PHP built in functions:
[code lang=”php”]
/* Create an Associate Array */
$clientInfo = array("name" => "Vinay Gulati", "city" => "Toronto", "country" => "Canada");
/* Print an Array */
print "Original Array is: ";
print_r($clientInfo);
/* Reverse an array without using PHP function */
print "Reversed Array without using any inbuilt PHP function is: ";
$tmp_Array=$clientInfo;
$index=array();
unset($clientInfo);
$i=0;
foreach ($tmp_Array as $key => $value) {
$index[$i]=$key;
$i++;
}
for($i; $i>0;$i–) {
$clientInfo[$index[$i-1]]=$tmp_Array[$index[$i-1]];
}
print_r($clientInfo);
[/code]
Original Array is: Array ( [name] => Vinay Gulati [city] => Toronto [country] => Canada )
Reversed Array without using any inbuilt PHP function is: Array ( [country] => Canada [city] => Toronto [name] => Vinay Gulati )
