Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP associative Array

Tags:

arrays

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

like image 434
Andromeda Avatar asked Feb 26 '26 19:02

Andromeda


1 Answers

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++;
}
like image 151
Zahymaka Avatar answered Mar 01 '26 07:03

Zahymaka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!