Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Change color of text based on $value

Tags:

php

colors

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.

like image 215
Kevin Brown Avatar asked May 10 '10 15:05

Kevin Brown


People also ask

How can I change the color of text in PHP?

<br />'; // display strings within paragraph with different color. echo "<p> <font color=blue>One line simple string in blue color</font> </p>"; echo "<p> <font color=red>One line simple string in red color</font> </p>"; echo "<p> <font color=green> One line simple string in green color</font> </p>"; ?>

How do you change the text color of an element text color?

So, different colored text elements are added to enhance the visuals of the webpage. The CSS color property defines the text color for an HTML element. For setting text-color for different elements in CSS, add the appropriate CSS selector and define the color property with the required color value.

How do you change the color of a string in HTML?

To set the font color in HTML, use the style attribute. The style attribute specifies an inline style for an element. The attribute is used with the HTML <p> tag, with the CSS property color. HTML5 do not support the <font> tag, so the CSS style is used to add font color.


3 Answers

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>
like image 58
sshow Avatar answered Oct 06 '22 17:10

sshow


$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>";
like image 35
LukeN Avatar answered Oct 06 '22 17:10

LukeN


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>
like image 30
mip Avatar answered Oct 06 '22 17:10

mip