css - Change background color for 4 results using php


Keywords:php 


Question: 

Using php i would like to change the background color of td depending what number is in it. I know that this can be done with css by just adding a class to each td with the color i want. But i want this to be simple for me to update!

Is there a way using php that i can just change a digit from 0 to one and it will automatically change the background color when displayed.

<table>
    <tbody>
        <tr><td>0</td></tr>
        <tr><td>1</td></tr>
        <tr><td>2</td></tr>
        <tr><td>3</td></tr>
    </tbody>
</table>

I presume the code would read something like the following but i have no idea how to code it.

if something equals 1 echo <td style="background:#f0f571;">1</td>
else if something equals 2 echo <td style="background: #ffc30f;">2</td>
else if something equals 3 echo <td style="background: #ff0000;">3</td>
else echo <td style="background: #498237;">0</td>

Then just have something like the following, then i can just change the number to 0, 1,2 or 3

<?php echo $something = 1;?>

2 Answers: 

Assuming all of this is being generated on the server side, you could create a supporting function like this:

function getBackgroundHex($v)
{
    $hex = '#498237'; // Default

    switch ($v) {
        case 1:
            $hex = '#f0f571';
            break;
        case 2:
            $hex = '#ffc30f';
            break;
        case 3:
            $hex = '#ff0000';
            break;
    }
    return $hex;
}

And where the HTML is rendered:

<table>
    <tbody>
<?php foreach ($value as $v) { ?>
        <tr><td style="background: <?php getBackgroundHex($v); ?>"><?php echo $v; ?></td></tr>
<?php } ?>
    </tbody>
</table>
 

Coloring should definitely be done in css, and not in php. Inline styles are (almost) always a bad idea, since your are mixing style and markup.

I understand your concern about maintainability however, so I would suggest doing something like this:

Where you now do something like this (I presume):

echo "<tr><td>$myValue</td></tr>";

You could just as easy do something like this:

echo "<tr><td data-content='$myValue'>$myValue</td></tr>";

And in your css you could target those cells like so:

td[data-content="1"] { color: red; }
td[data-content="2"] { color: green; }