One Circle Software
One Circle Software

Reputation: 13

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

Upvotes: 0

Views: 209

Answers (2)

jspit
jspit

Reputation: 7713

$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

Upvotes: 1

Sami Akkawi
Sami Akkawi

Reputation: 342

rsort($nilai); // this will sort your array
$arrayCount = count($nilai); // get the number of enties
$maxFive = array_slice($nilai, 0, 5);
$minFive = array_slice($nilai, $arrayCount-5, $arrayCount);

Upvotes: 1

Related Questions