0

I have a array both key & value are string like

 $myArr = array(
     'ball'=>'zebra', 
     'tree'=>'plant', 
     'zoo'=>'animal' );

I need to sort array by its values and keep key, value association, so output would be like

 $sortedArr = array(
     'zoo'=>'animal', 
     'tree'=>'plant', 
     'ball'=>'zebra' ); 

I am looking for shortest and smartest solution to achieve this, if you have that one please share with me.

Nabin Kunwar
  • 1,965
  • 14
  • 29
Ramesh Mhetre
  • 404
  • 2
  • 12

4 Answers4

3

Take a look at asort:

$myArr = array('ball'=>'zebra', 'tree'=>'plant', 'zoo'=>'animal');
asort($myArr);

echo print_r($myArr, TRUE);

Result:

Array
(
    [zoo] => animal
    [tree] => plant
    [ball] => zebra
)
joao
  • 292
  • 2
  • 7
1

Ramesh, you can also try this one.

function csort($a, $b) {
if ($a == $b) {
    return 0;
}
return ($a < $b) ? -1 : 1;
}
$myArr = array('ball'=>'zebra', 'tree'=>'plant', 'zoo'=>'animal');
uasort($myArr, 'csort');
print_r($myArr);
exit;
Ram Sharma
  • 8,676
  • 7
  • 43
  • 56
0

You can use any on the inbuilt php function listed here http://php.net/manual/en/array.sorting.php

The all sorts by value and maintain key association

Veerendra
  • 2,562
  • 2
  • 22
  • 39
0

I found solution.

asort($myArr);
Ramesh Mhetre
  • 404
  • 2
  • 12