Forum Moderators: coopster

Message Too Old, No Replies

help with displaying php variable

php html

         

ksugam

12:25 am on Feb 1, 2008 (gmt 0)

10+ Year Member



Hello,
i am storing the values from mysql into php variables. the sample values are as follows:
$val=2.35
$val=-3.5
$val=-6.8

this can be a positive value or a negative value.

I need to output the variable in html depending on its value. If the value is negative, display it in red (e.g. if $val=-25., display 2.5 in red color). If it is positive, display it in green (e.g. if $val=25., display 2.5 in green color)

Would appreciate any help

Thanks!

DaimonR

3:45 am on Feb 1, 2008 (gmt 0)

10+ Year Member



if($val > 0){
echo "<font color='green'>";
}
else{
echo "<font color='red'>";
}
echo $val;
echo "</font>";

While I'm sure there are more elegant ways to do this, this is what I would do. Hope it helps.

coopster

4:45 pm on Feb 1, 2008 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Welcome to WebmasterWorld, ksugam and DaimonR.

Another way to do it would be to use CSS and a class. Here, I'll demonstrate the ternary conditional operator [php.net]:

<style type="text/css"> 
p.red {
color: red;
}
p.green {
color: green;
}
</style>
<p class="<?php print $val < 0? 'red' : 'green'; ?>"><?php print $val; ?></p>

ksugam

5:43 pm on Feb 1, 2008 (gmt 0)

10+ Year Member



thanks guys! It works..but i have one more doubt...
I don't need the negative sign in the value because 'red' represents negative and green represents positive...
How do i do tht....sorry for such a silly doubt

PHP_Chimp

10:36 pm on Feb 1, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member




if ($val < 0) {
$val = [url=http://uk3.php.net/manual/en/function.substr.php]substr[/url]($val, 1);
}

As this will remove the first character from the string assuming the string is less than 0.

<edit>
You can use the ternary operator for this as well, but an if block may well be easier to read ;)

[edited by: PHP_Chimp at 10:39 pm (utc) on Feb. 1, 2008]

maxximus

11:27 pm on Feb 1, 2008 (gmt 0)

10+ Year Member



Abs should be used for numerics.

[uk3.php.net...]