Skip to content
Advertisement

how to display the maximum and minimum value of 5 data in an array

I created a php script to find the minimum and maximum values, but only 1 array data was detected, I want 5 maximal data and 5 minimum data, how it’s work?

    <?php
                                               
$nilai = array("70", "75", "72", "71", "90", "55", "24", "74", "66", "30", "99", "100", "15", "47", "96"); //Array Nilai
echo "Nilai Siswa : "; //Tampilkan Tulisan Nilai Siswa
echo implode (", ", $nilai, ); //Tampilkan Data Array

$tinggi=max($nilai); //Nilai Maximal
$rendah=min($nilai); //Nilai Minimal

echo "<br>Daftar Nilai Terendah : $rendah";  // Tampilkan Nilai Minimal
echo "<br>Daftar Nilai Tertinggi: $tinggi <br>";  // Tampilkan Nilai Maximal
?>

Advertisement

Answer

$input = array("70", "75", "72", "71", "90", "55", "24", "74", "66", "30", "99", "100", "15", "47", "96");
sort($input);
$min5 = array_slice($input,0,5);
$max5 = array_slice($input,-5,5);

echo '<pre>';
var_dump($min5,$max5); 

output:

array(5) {
  [0]=>
  string(2) "15"
  [1]=>
  string(2) "24"
  [2]=>
  string(2) "30"
  [3]=>
  string(2) "47"
  [4]=>
  string(2) "55"
}
array(5) {
  [0]=>
  string(2) "75"
  [1]=>
  string(2) "90"
  [2]=>
  string(2) "96"
  [3]=>
  string(2) "99"
  [4]=>
  string(3) "100"
}

If the data is to be output as a list, this can be done with implode.

echo implode(',',$min5); //15,24,30,47,55

If the list of maximum values ​​should start at the highest value, $ max5 must be sorted again with rsort.

rsort($max5);
echo implode(',',$max5); //100,99,96,90,75
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement