简体   繁体   中英

How to get 7 highest value from the array

I want to get 7 highes values from my array, but it should be sorted properly

I have this code:

<?php    
$nilai = array(72,65,73,78,75,74,90,81,87,65,55,69,72,78,79,91,100,40,67,77,86);
$jumlah = 0;
for ($i = 0; $i <= count($nilai)-1; $i++)
{
    $jumlah += $nilai[$i];
}
$rata = $jumlah/count($nilai);
$max = $nilai[0];
for ($i = 0; $i <= count($nilai)-1; $i++)
{
    if ($nilai[$i] > $max)
    {
        $max = $nilai[$i];
    }
    rsort($nilai);
    $top7 = array_reverse(array_slice($nilai, 0, 7));
}
echo "Rata-Rata : ".$rata;
echo "<br>";
echo "Tertinggi : ".$top7;
?>

Output :

Tertinggi : 100,91,90,87,86,81,79

Your code almost get the right output, except you cannot echo an array, you need to use print_r() or some other method to convert the array to a string.

But to make the code more compact, the following uses just the minimum (I can think of anyway) code...

$nilai = array(72,65,73,78,75,74,90,81,87,65,55,69,72,78,79,91,100,40,67,77,86);

// Average
$jumlah = array_sum($nilai);
$rata = $jumlah / count ( $nilai );
echo "Rata-Rata : ".$rata;
echo "<br>";

// Top 7
rsort($nilai);
$top7 = array_slice($nilai, 0, 7 );

echo "Tertinggi : ";
print_r($top7);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM