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?
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
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With