Here is my PHP code:
foreach ( $sums as &$sums_value ) {
if ( !empty($sums_value) ) {
$sums_value = sprintf("%+d",$sums_value);
}
} unset($sums_value);
$sums
contains some [positive or negative] numbers. Here is an example of $sums
's output:
/*
array (
[today] => +24
[yesterday] => -6
[in last week] => 0
[in last month] => 9
)
And I use it like this: (I generate a HTML)
$date = array ('today', 'yesterday', 'in last week', 'in last month');
foreach( $date as $item ) {
$html .= '<span>'.$sums[$item].'</span>';
} echo $html;
/* output:
<span>+24</span><span>-6</span><span>0</span><span>9</span>
Ok, all fine.
Well what's my question? It's about coloring. I want to set:
So I want this output:
<span style="color:green">+24</span><span style="color:red">-6</span><span style="color:black">0</span><span style="color:green">9</span>
As you see, I've added a style="color:????"
property to all those <span>
s which is dynamic. I mean that color depends on the number. How can I do that?
You can just test the sum in the loop:
$date = array ('today', 'yesterday', 'in last week', 'in last month');
foreach( $date as $item ) {
$sum = $sums[$item];
$color = '';
if ($sum < 0) {
$color = 'red';
} elseif ($sum > 0) {
$color = 'green';
} else {
$color = 'black';
}
$html .= '<span style="color:'.$color.';">'.$sums[$item].'</span>';
} echo $html;
simple php will do
echo 'style="color:';
if($sums[$item] == 0){
echo 'black';
}
else if($sums[$item] > 0){
echo 'green';
}
else{
echo 'red';
}
echo '"';
In your foreach you need to add an if statement.
foreach( $date as $item ) {
If($item = 0){
$html .= '<span style="color:black">' . $sums[$item] . '</span>';
}else if($item>0){
$html .= '<span style="color:green">' . $sums[$item] . '</span>';
}else{
$html .= '<span style="color:red">' . $sums[$item] . '</span>';
}
}
I think you can do it without PHP. only CSS3
but if you want use php. Take a look on example
function getColor($number) {
if ($number == 0) {
return 'black';
}
if ($number > 0) {
return 'green';
}
if ($number < 0) {
return 'red';
}
}
$date = array ('today', 'yesterday', 'in last week', 'in last month');
foreach( $date as $item ) {
$html .= '<span style="color:' . getColor($sums[$item]) . '">'.$sums[$item].'</span>';
} echo $html;