2

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 ???

4 Answers 4

7

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
  $i++;
}
Sign up to request clarification or add additional context in comments.

2 Comments

what if i want to sort in descending order?/
Oops, I forgot the $i++. Thanks Greg.
5

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

asort($asd);
$top_four_keys = array_slice(array_keys($asd), 0, 4);

Comments

2

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.