Jump to content

PHP: Change the color based on number.


php_admin

Recommended Posts

Hello,

I really need some help with solving a problem I have with a script on my site. I am not the most experienced in PHP, but I know the basics...

 

I have a weather script on my site that updates every 2 hours to show the current weather. For example, it could say "Partly Cloudy, 17°C" on the page.

I want to make the background color of this element change with the temperature of the weather. However, the temperature is a number, not a color. So how would I convert a number into how strong/dark the color is? I already made a script for the basic colors, but now I need to change the opacity based on the temperature.

 

if($temp < 10){
$temperature_color = "green";
} else if ($temp >= 10 && $temp < 20){
$temperature_color = "yellow";
} else if ($temp >= 20 && $temp < 30){
$temperature_color = "orange";
} else {
$temperature_color = "red";
}

 

Maybe the code could be something like:

if($temp < 10){
$opacity = $temp * 10;
} else if ($temp >= 10 && $temp < 20){
$opacity = $temp * 5;
} else if ($temp >= 20 && $temp < 30){
$opacity = $temp * 3.3;
} else {
$opacity = $temp * 2.5;
}

 

Any ideas on how to do this?

Thank you! Any and all help is appreciated.

 

--m

Link to comment
https://forums.phpfreaks.com/topic/161288-php-change-the-color-based-on-number/
Share on other sites

<?php
switch(true)
{
  case $temp < 10:
    $temperature_color = 'green';
    $opacity = $temp*10;
    break;
  case $temp < 20:
    $temperature_color = 'yellow';
    $opacity = $temp*5;
    break;
  case $temp < 30:
    $temperature_color = 'orange';
    $opacity = $temp*3.3;
    break;
  default:
    $temperature_color = 'red';
    $opacity = $temp*2.5;
}
?>

<?php
switch(true)
{
  case $temp < 10:
    $temperature_color = 'green';
    $opacity = $temp*10;
    break;
  case $temp < 20:
    $temperature_color = 'yellow';
    $opacity = $temp*5;
    break;
  case $temp < 30:
    $temperature_color = 'orange';
    $opacity = $temp*3.3;
    break;
  default:
    $temperature_color = 'red';
    $opacity = $temp*2.5;
}
?>

 

Thank you.  ;D

 

Now, I just have to find a way to transfer the opacity value to CSS... unfortunately I can't just use the

opacity

command, because it isn't supported in all browsers.  >:(

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.