Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get top 3 values in php array and their index

I want to get the highest value, the second highest value and the third highest value

For example, I have an array like:

$n = array(100,90,150,200,199,155,15,186);

I know the method to get the max value and its index:

echo max($n); //200 $maxs = array_keys($n, max($n)); echo $maxs[0]; //3

I want to get the top 3 values and their index like : value: 200, 199, 186 index:3,4,7

How can i get them?

like image 515
user3533254 Avatar asked Apr 27 '14 16:04

user3533254


2 Answers

Try this:

$n = array(100,90,150,200,199,155,15,186);
rsort($n);
$top3 = array_slice($n, 0, 3);
echo 'Values: ';
foreach ($top3 as $key => $val) {
 echo "$val\n";
}
echo '<br>';
echo 'Keys: ';
foreach ($top3 as $key => $val) {
echo "$key\n";
}

Output:

Values: 200 199 186 
Keys: 0 1 2
like image 67
Nadeem Khan Avatar answered Oct 06 '22 13:10

Nadeem Khan


This should do the trick:

function maxNitems($array, $n = 3){
    asort($array);
    return array_slice(array_reverse($array, true),0,$n, true);
}

Use like:

maxNitems(array(100,90,150,200,199,155,15,186));
like image 28
Michael Seibt Avatar answered Oct 06 '22 13:10

Michael Seibt