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



Solution 1:[1]

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

Solution 2:[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));

Solution 3:[3]

You can achieve it by using arsort() and array_keys() functions:

  • arsort() sorts an array in reverse order and maintains index association
  • array_keys() returns all the keys or a subset of the keys of an array

Process array:

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

Get top 3 values:

echo $n[$keys[0]];
echo $n[$keys[1]];
echo $n[$keys[2]];

Solution 4:[4]

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

$x = 0;
while (++$x <= 3)
{
    $key = key($n);
    $value = current($n);
    next($n);
    echo "Key : " . $key . " Value  : " . $value . '<br>' ;
}

Solution 5:[5]

Easier I would think:

arsort($n);
$three = array_chunk($n, 3, true)[0];
//or
$three = array_slice($n, 0, 3, true);

Solution 6:[6]

try this:

public function getTopSortedThree(array $data, $asc = true)
{
    if ($asc) {
        uasort($data, function ($a, $b) { return $a>$b;});
    } else {
        uasort($data, function ($a, $b) { return $a<$b;});
    }
    $count = 0;
    $result = [];
    foreach ($data as $key => $value) {
        $result[] = $data[$key];
        $count++;
        if ($count >= 3){
            break;
        }
    }
    return $result;
}

send false for desc order and nothing for asc order

This functionality doesn't losing keys.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Josh Crozier
Solution 3
Solution 4 Pankaj Garg
Solution 5 AbraCadaver
Solution 6 Faesal