Skip to content

Sort an array of temperatures in ascending order and retrieve 5 coolest and 5 warmest temperatures.

Notifications You must be signed in to change notification settings

chiragobhan/php-arrays

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 

Repository files navigation

PHP Arrays

Sort an array of temperatures in ascending order and retrieve 5 coolest and 5 warmest temperatures.

Initialize array

$array = array(68, 70, 72, 58, 60, 79, 82, 73, 75, 77, 73, 58, 63, 79, 78, 68, 72, 73, 80, 79, 68, 72, 75, 77, 73, 78, 82, 85, 89, 83);

Print array

print_r($array);

Output:

printArray

Sort array in ascending order

for ($j = 0; $j < count($array); $j++) {
  for ($i = 0; $i < count($array) - 1; $i++) {
    if ($array[$i] > $array[$i + 1]) {
      $temp = $array[$i + 1];
      $array[$i + 1] = $array[$i];
      $array[$i] = $temp;
    }
  }
} 

Average of all tempratures

$total = 0;
foreach ($array as $key => $value) {
  $total = $total + $value;
}
echo ($total / count($array)) . ' is the average of the temperatures.';

Output:

average

Five coolest tempratures

$max = count($array);  
for ($i = $max - 5; $i < $max; $i++) {  
  echo "$array[$i]℉ temperature";  
}

Output:

coolest

Five warmest tempratures

for ($i = 0; $i < 5; $i++) {  
  echo "$array[$i]℉ temperature";  
}

Output:

warmest

About

Sort an array of temperatures in ascending order and retrieve 5 coolest and 5 warmest temperatures.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages