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.

6
  • 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 :) Commented May 10, 2010 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. Commented May 11, 2010 at 6: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. Commented May 11, 2010 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 ;) Commented May 11, 2010 at 15:50
  • I'd trade my gold badge for your knowledge any day! :) Commented May 11, 2010 at 17:35

14 Answers 14

11
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>
Sign up to request clarification or add additional context in comments.

7 Comments

Is a function overkill for a simple operation like this?
If you keep an external file for functions, as I always do, I'd say this is a more readable way to do it.
A function is probably your best bet in terms of clarity and organization.
You're right. I'm passing several variables through, and the function definitely was the solution!
Unbelievable - the wrong answer gets the green tick! This answer has been edited and still does not follow the OP rules.
|
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>";

6 Comments

You switched between $v and $var in the second if block. ;)
+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).
This answer has "Greater than OR EQUAL to 11" to be red. Not the same as "Greater than"..
So what's in the case of $v being equal to 11? Black again?
@LukeN We don't know. The OP has failed to clarify what happens when n=11.
|
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>

Comments

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>

Comments

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';

1 Comment

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.
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>

Comments

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>";

3 Comments

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).
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
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.
1

Ternary operator for your simple example.

  $color = ($var < 6) ? '#FF8000' :  (($var < 10) ? '#00FF00' : '#FF0000');

Comments

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?

Comments

0

I found this plugin:

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

Comments

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

1 Comment

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
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>

Comments

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';

2 Comments

Probably is...hard to say what I was thinking 8 years ago.
just an idea i had when i saw this post and maybe it will help some people who come to this page ( like i did yesterday :) )
-1
$color="green";
$text="foo";
echo wrapColor($color, $text);

function wrapColor($color, $text){
return "<span style=color:$color>$text</span>";
}

1 Comment

This example doesn't really address @Kevin Brown's question; it will always print out <span style=color:green>foo</span> (which is not what he was asking for)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.