6

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.

PeeHaa
  • 71,436
  • 58
  • 190
  • 262
Kevin Brown
  • 12,602
  • 34
  • 95
  • 155
  • Fun thing is when the answers are so darn similar! I just noticed mine and sshow's are (except for the function part and the orange color hex) exactly the same :) – LukeN May 10 '10 at 16:24
  • @Kevin, this question is turning out to be a nightmare. I was in the middle of down voting everyone who did not match your rules but at the end of the day you should edit your question or acknowledge that most of the answer are wrong - including the green tick answer. Just so you (and others) understand "Greater than 11" is not the same as "Greater than or equal to 11". Some of the answers are wrong for other obvious reasons. But, hey, this is a public Q&A site and we should expect this kind of behavior. – zaf May 11 '10 at 06:25
  • @Zaf, I realize that technicaly, they are wrong because the said >= 11. But the fact remains that they answered MY QUESTION (it's the line that ends with a "?"). My example was simply to provide more detail and facilitate an answer applicable to my situation. sshow answered well and you're just jealous. – Kevin Brown May 11 '10 at 15:41
  • @Kevin Not jealous of sshow at all, if I was him I'd change his answer otherwise it's not a very good record. I am jealous of your gold badge tho ;) – zaf May 11 '10 at 15:50
  • I'd trade my gold badge for your knowledge any day! :) – Kevin Brown May 11 '10 at 17:35
  • @Kevin And I'll trade it back for being 21 again. – zaf May 13 '10 at 09:27

14 Answers14

10
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>
sshow
  • 8,820
  • 4
  • 51
  • 82
  • Is a function overkill for a simple operation like this? – Kevin Brown May 10 '10 at 16:13
  • If you keep an external file for functions, as I always do, I'd say this is a more readable way to do it. – sshow May 10 '10 at 16:15
  • 1
    A function is probably your best bet in terms of clarity and organization. – ggfan May 10 '10 at 16:17
  • You're right. I'm passing several variables through, and the function definitely was the solution! – Kevin Brown May 10 '10 at 16:35
  • Unbelievable - the wrong answer gets the green tick! This answer has been edited and still does not follow the OP rules. – zaf May 10 '10 at 16:37
  • @Kevin and I suppose @sshow, you wanted "Greater than 11" to be red. This answer is "Greater than OR EQUAL to 11" to be red. Spot the difference now? – zaf May 11 '10 at 06:14
  • Technically, the OP also asked for values *between* 1 and 5, and *between* 6 and 10, and *greater* than 11; which means 1, 5, 6, 10, and 11 are all excluded from consideration. Most people who answered (including myself) read into the question that perhaps Kevin didn't word it completely literally (sorry Kevin if you did). So we took it to mean that 1 *through* 5 are green, 6 *through* 10 are orange and anything 11 and greater are red. – JYelton May 17 '10 at 15:04
5
$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>";
LukeN
  • 5,590
  • 1
  • 25
  • 33
  • 1
    You switched between `$v` and `$var` in the second if block. ;) – ABach May 10 '10 at 16:08
  • +1 this is probably the best solution, and doesn't have any "open-ended" evaluations (such as in mine which will happily take values less than 1 and still use green color). – JYelton May 10 '10 at 17:22
  • This answer has "Greater than OR EQUAL to 11" to be red. Not the same as "Greater than".. – zaf May 11 '10 at 06:16
  • So what's in the case of $v being equal to 11? Black again? – LukeN May 11 '10 at 11:25
  • @LukeN We don't know. The OP has failed to clarify what happens when n=11. – zaf May 13 '10 at 09:25
  • I think, sometimes healthy assumption is okay. This looks like some rating system where low = good and high = bad, so there'd be no sense in leaving undefined spots in the definition. :) – LukeN May 13 '10 at 11:07
4

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>
mip
  • 8,355
  • 6
  • 53
  • 72
2

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>";
JYelton
  • 35,664
  • 27
  • 132
  • 191
  • Be careful - in this particular example, anything from 0 - 5 (well, technically, -infinity to 5, but you get the idea) will always be assigned '#FF8000' (which I don't believe is correct). – ABach May 10 '10 at 16:06
  • anything less than 5 wont work since it would be overwritten since anything less than 5 will be less than 10. One can use elseif to get out of this situation – nik May 10 '10 at 16:11
  • My original answer had the if statements in an order that would cause a problem, where <6 was evaluated before <10. Technically elseif's would be better. I left this as original, but changed the order so that they'll work properly. My apologies on the original one, I was just aiming for something that was easy to read. – JYelton May 10 '10 at 17:19
2

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>
Rik Heywood
  • 13,816
  • 9
  • 61
  • 81
2

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';
fafnirbcrow
  • 270
  • 3
  • 8
  • If $var == 10 this will not set $color, though you're right, elseif's are better than a trio of if's, as in my answer. – JYelton May 10 '10 at 17:20
2

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>
zaf
  • 22,776
  • 12
  • 65
  • 95
1

Ternary operator for your simple example.

  $color = ($var < 6) ? '#FF8000' :  (($var < 10) ? '#00FF00' : '#FF0000');
alexganose
  • 237
  • 4
  • 12
0

Assuming one works with ranges than this is quite flexible:

function getProperColor($range, $value)
{
    foreach($range as $key => $color)
    {
        if ($value <= $key)
            return $color;
    }
    return $color;
}

$colorRange = array(
    5 => 'green',
    10 => 'orange',
    11 => 'red'
);

for($i=-1;$i<16;$i+=2)
{
    echo "$i:" . getProperColor($colorRange, $i) . "\n";
}

This will output:

-1:green
1:green
3:green
5:green
7:orange
9:orange
11:red
13:red
15:red
Finzzownt
  • 380
  • 3
  • 6
  • 2
    Kevin, I found this post, so other people may too. And all suggestions were about using if statements. Thought I'd share using a range, thereby separating data from logic. Is – Finzzownt Jul 13 '13 at 14:02
0
<?php
$var='2';
?>
 <html>
  <body>
   <p>Hello Welcome.I am
     <?php 
      if($var>0 && $var<=5)
        echo '<p style=color:Green;>';
      else if($var>=6 && $var<= 10)
        echo '<p style=color:orange;>';
      else
         echo '<p style=color:red;>';
?>
        I am a Developer.
     </p>
     </body>
Alekhya
  • 41
  • 5
0

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?

acm
  • 6,541
  • 3
  • 39
  • 44
0

I found this plugin:

http://www.jnathanson.com/blog/client/jquery/heatcolor/index.cfm#examples

Kevin Brown
  • 12,602
  • 34
  • 95
  • 155
0

why not a switch case ? it would be cleaner this way

   $color = "";
   switch(true){
      case ($var > 0 && $var <= 5):
            $color = '#00FF00';
      break;
      case ($var >= 6 && $var <= 10):
            $color = '#00FF00';
      break;
      case ($var >= 11):
            $color = '#00FF00';
      break;
      default:
            $color = '#000000';
JeremyGi
  • 86
  • 10
-1
$color="green";
$text="foo";
echo wrapColor($color, $text);

function wrapColor($color, $text){
return "<span style=color:$color>$text</span>";
}
Chad
  • 364
  • 2
  • 7
  • 1
    This example doesn't really address @Kevin Brown's question; it will always print out `foo` (which is not what he was asking for) – ABach May 10 '10 at 16:10