With below code I am trying to change background color of td element. I think code needs correction, any help please. It's not applying color. or any other better solution.
PHP code:
$color = "#000000";
if (($change[array_keys($change)[0]] < 0))
$color = "#E54028";
else if (($change[array_keys($change)[0]] >= 1) && ($change[array_keys($change)[0]] <= 19))
$color = "#F18D05";
else if ($change[array_keys($change)[0]] >= 20)
$color = "#61AE24";
Td element:
<td <?php echo "style=background: $color";?>><?php echo $change[array_keys($change)[0]];?>%</td>
hm, did you tried this? https://www.w3schools.com/cssref/pr_background-color.asp
<?php echo "style='background-color:{$color};' "; ?>
Are your td
tags in the table
? The td
tag must be the table cell and attribute of html tag must be quoted by "
or '
. following code is work fine on me.
<?php
$change['a'] = 10;
$color = "#000000";
if ($change[array_keys($change)[0]] < 0)
$color = "#E54028";
else if (($change[array_keys($change)[0]] >= 1) && ($change[array_keys($change)[0]] <= 19))
$color = "#F18D05";
else if ($change[array_keys($change)[0]] >= 20)
$color = "#61AE24";
?>
<table>
<td <?php echo "style=\"background: $color\"";?>><?php echo $change[array_keys($change)[0]];?>%</td>
</table>
When you face repetitive elements you should use foreach
loop. It is easy in this situation, you just add foreach
outside those code like this:
<?php
foreach ($change as $item) {
$color = "#000000";
if ($item < 0)
$color = "#E54028";
else if (($item >= 1) && ($item <= 19))
$color = "#F18D05";
else if ($item >= 20)
$color = "#61AE24";?>
<td <?php echo "style=\"background: $color\"";?>><?php echo $item;?>%</td>
<?php } ?>
Normally a table is composed of two-dimensional array so loop twice can do it, but if the situation in your form is more complicated you can not do that. You can create a function and call them when needed if you just want to simply achieve your need. Because I do not know your specific needs so I can only give you this simple suggestion.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.