What's the easiest way to change a text's color based on a variable?
For example: If $var is between 1-5, green. Between 6-10, Orange. Greater than 11, Red.
What's the easiest way to change a text's color based on a variable?
For example: If $var is between 1-5, green. Between 6-10, Orange. Greater than 11, Red.
Something like this trio of if statements:
if ($var < 10) $color = '#FF8000';
if ($var < 6) $color = '#00FF00';
if ($var >= 10) $color = '#FF0000';
echo "<span style=\"color: $color;\">This text is colored.</span>";
$color = "#000000";
if (($v >= 1) && ($v <= 5))
$color = "#00FF00";
else if (($v >= 6) && ($v <= 10))
$color = "#FF9900";
else if ($v >= 11)
$color = "#FF0000";
echo "<span style=\"color: $color\">Text</span>";
A simple solution might be to do something like this...
if ($var < 6)
$style="0F0";
else if ($var < 11)
$style="F50";
else
$style = "F00";
?><div style="color:#<?php echo $style; ?>">blar</div>
function getProperColor($number)
{
if ($var > 0 && $var <= 5)
return '#00FF00';
else if ($var >= 6 && $var <= 10)
return = '#FF8000';
else if ($var >= 11)
return = '#FF0000';
}
And use it like this
<div style="background-color: <?=getProperColor($result['number'])?>;"><?=$result["title"]?></div>
You need to actually use elseif statements if your going to use a set of if statements,
if ($var < 6) $color = '#00FF00';
elseif ($var < 10) $color = '#FF8000';
elseif ($var > 10) $color = '#FF0000';
$color="green";
$text="foo";
echo wrapColor($color, $text);
function wrapColor($color, $text){
return "<span style=color:$color>$text</span>";
}
Are color values indexed by constants? I would prepare hash map
$colorMap[0] = '#00FF00'; //green
$colorMap[1] = '#0000FF'; //blue
$colorMap[2] = '#FF0000'; //red
$colorMap[3] = '#330000'; //dark red
and so on. Then use CSS
<span style="color: <?php echo $colorMap[$var]; ?>;">desired color</span>
I'll use CSS colors and also highlight the fact that the number 11 does not map to any color according to your rules making most of the answers invalid :)
<?php
$color=getColor(11);
function getColor($n){
// Is number between 1 and 5?
if($n>=1 && $n<=5) return "green";
// Is number between 6 and 10?
if($n>=6 && $n<=10) return "orange";
// Is number greater than 11
if($n>11) return "red";
// Return default (black) for all other numbers
return "black";
}
?>
<span style='color:<?=$color?>'>Text</span>
I would use CSS classes instead of inline styling the color... Let CSS work...
<?php
$var = 5;
$class = (($var < 6) ? 'greenclass' : (($var < 11) ? 'orangeclass' : 'redclass' ))
?>
<span class="<?php echo $class?>">text</div>
If none of these answers are the one you expect, what exactly are you trying to accomplish? Can you give more info?
Ternary operator for your simple example.
$color = ($var < 6) ? '#FF8000' : (($var < 10) ? '#00FF00' : '#FF0000');