I am receiving data from an XML with info about the weather from some locations. I am fetching info about the temperature, which I want to display like this:
If the temperature is above 13, the numbers shall be displayed in red
If the temperature is between or equal to 0 and 12, the numbers shall be displayed in white
If the temperature is lower than 0, the numbers shall be displayed in blue
I have currently tried this:
if ($result[0]['temperature'] > 13){
$temperature = "<span style='color:#FD1B1C;'>". $result[0]['temperature']. "°"."</span>";
}
if ($result[0]['temperature'] >=0 && $result[0]['temperature'] <=12){
$temperature = "<span style='color:white;'>". $result[0]['temperature']. "°"."</span>";
}
if ($result[0]['temperature'] < 0){
$temperature = "<span style='color:blue;'>". $result[0]['temperature']. "°"."</span>";
}
This code^ works but soon gets very long and "unclear". This $temperature
is only one temperature and when I want to show 7 temperatures (one for each day in a week) and for multiple locations, I soon get very many ´$temperature n` variables and lines. Example: one temperature like I have shown is 9 lines of code. When I want to show it for 7 days and 3 locations it's 9x7*3 = 189 lines + spacing, you get the idea.
Maybe the best is to have this code in another file and just refer to it?
For info:
The XML shows temperatures for each 6 hours (0-6, 6-12, 6-18, 18-24) this means I fetch $result[0],[4],[8],[12]
to get for each day.
Make an array of breakpoints, and assign the color based on the breakpoint:
function getColor($temp) {
$defaultColor = 'blue';
$breakPoints = [
'0' => 'white',
'13' => 'red',
];
$out = $defaultColor;
foreach($breakPoints as $target => $color) {
if ( (float)$target <= (float)$temp) {
$out = $color;
}
}
return $out;
}
Since we set up the breakpoints in ascending order, we set the default color to be the color for negative values. Then, as we iterate through the breakpoints, keep changing the color until the breakpoint is greater than the temperature being tested.
Note that putting this in a function allows it to be used throughout your script:
<?php
// do all your php stuff, including the getColor function
?>
<!-- html stuff -->
<?php foreach($result as $row): ?>
<!-- display the row in html -->
<div>The temperature is
<span style="color:<?= getColor($row['temperature']) ?>">
<?= $row['temperature'] ?> °
</span>
</div>
<?php endforeach; ?>