Horakhty
Horakhty

Reputation: 11

How to show more than 1 data in php array after doing min and max

I'm doing my homework and I can't find the solution to displaying more than one result in array after doing min and max syntax

my teacher said that I should use min and max to show more than 1 result

$temperatures = [78, 60, 62, 68, 71, 68, 73, 85, 66, 64, 76, 63, 75, 76, 73, 68, 62, 73, 72, 65, 74, 62, 62, 65, 64, 68, 73, 75, 79, 73];
$max = max($temperatures);
$min = min($temperatures);

The final result should be:

average of the temperatures : 70.6
the five lowest temperature lists : 60, 62, 63, 63, 64
the five highest temperature lists : 76, 78, 79, 81, 85

Upvotes: 0

Views: 54

Answers (1)

treyBake
treyBake

Reputation: 6558

My two cents on it:

$temperatures = [78, 60, 62, 68, 71, 68, 73, 85, 66, 64, 76, 63, 75, 76, 73, 68, 62, 73, 72, 65, 74, 62, 62, 65, 64, 68, 73, 75, 79, 73];

# simply sum the elements then divide by count
$avg = (array_sum($temperatures) / count($temperatures));

# sort arr low -> high
sort($temperatures);
# make els unique
$temperatures = array_unique($temperatures);

$min = array_slice($temperatures, 0, 5); # get first 5 in array
$max = array_slice($temperatures, -5); # get last 5 in array

echo '<pre>'. print_r($avg, 1) .'</pre>';
echo '<pre>'. print_r($min, 1) .'</pre>';
echo '<pre>'. print_r($max, 1) .'</pre>';

Upvotes: 4

Related Questions