Andromeda
Andromeda

Reputation: 12897

PHP associative Array

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

Upvotes: 2

Views: 794

Answers (4)

MiffTheFox
MiffTheFox

Reputation: 21555

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.

Upvotes: 2

risyasin
risyasin

Reputation: 1321

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.

Upvotes: 0

Zahymaka
Zahymaka

Reputation: 6621

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++;
}

Upvotes: 7

Sander Marechal
Sander Marechal

Reputation: 23216

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

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

Upvotes: 5

Related Questions