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 ???
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 ???
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.
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
}
An alternative to the other answers. This one without a loop:
asort($asd);
$top_four_keys = array_slice(array_keys($asd), 0, 4);
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.