tags:

views:

324

answers:

4

I have an associative array in PHP

$asd['a'] = 10;
$asd['b'] = 1;
$asd['c'] = 6;
$asd['d'] = 3;

i want to sort this on basis of its value and to get the key value for the first 4 values.

how can i do that in php ???

+2  A: 

The asort function's what you need to sort it.

To get the values, you can use code like this:

$myKeys = array_keys(asort($asd));
$myNewItems = Array();
for ($i = 0; $i < 4; $i++)
    $myNewItems[$myKeys[$i]] = $asd[$myKeys[$i]];

Which will put the first fur items into $myNewItems, with the proper keys and sort order.

MiffTheFox
+6  A: 

asort() should keep the index association:

asort($asd);

After that, a simple foreach can get you the next four values

$i = 0;
foreach ($asd as $key=>$value)
{
  if ($i >= 4) break;
  // do something with $asd[$key] or $value
}
Zahymaka
+1 but might want to i++ somewhere in there :)
Greg
what if i want to sort in descending order?/
Jasim
http://php.net/arsort
Matthew Scharley
Oops, I forgot the $i++. Thanks Greg.
Zahymaka
+6  A: 

An alternative to the other answers. This one without a loop:

asort($asd);
$top_four_keys = array_slice(array_keys($asd), 0, 4);
Sander Marechal
A: 

i would like to add... asort($asd,SORT_NUMERIC); $top_four_keys=array_slice(array_keys($asd), 0, 4);

for descending order: arsort($fruits,_SORT_NUMERIC); $top_four_keys=array_slice(array_keys($asd), 0, 4);

you may need to use SORT_NUMERIC parameter, in case of you have an unexpected array.

risyasin