在php中关闭条件设置颜色[关闭]

How do I set a color by condition eg:

In my table there is a column called STATUS where receive the result from db. with three texts: PG, PEN, ATR.

If status is PG, then color green, PEN color red etc..

How to do that?

My current code is <th width="4%" scope="col"><?php echo $status;?></th>

Set a class on your HTML display, you could even make it class="PG" for example in case you decide to change the color of it later. Then you define the color of that class in css.

Using the example code you provided:

<th width="4%" scope="col" class="<?php echo $status;?>"> <?php echo $status;?></th>

CSS file would include:

.PG {text-color:green;} 
.PEN {text-color:red;} 

Note: not sure if by color you meant background-color or text-color; either works.

You can set color in an array and you can assign them easily as below.

 $color = array (
        "PG"=>"green", // use color code here
        "PEN"=>"red"
       );

In html, you call the status color from array:

<tr style='background-color:<?php echo $color[$row["status"]];?>'>
<td>....</td>

</tr>

There are three ways you can do it (and probably a few others as well), but here are my three ways: set the value of the style, rewire the entire text, or inline php color setting... Here are the three ways below, from the best to worst, in my opinion.

Set Value of the style method

$style = '';

if ( $status == 'PG' )
    $style = 'style="color: green;"'; // You can replace with class=""
else if ( $status == 'PEN' )
    $style = 'style="color: red;"'; // You can replace with class=""
else if ( $status == 'ART')
    $style = 'style="color: blue;"'; // You can replace with class=""

?>

<th width="4%" scope="col" <?=$style?> ><?=$status?></th>

Rewrite entire line method

<?php

if ( $status == 'PG' )
    echo '<th width="4%" scope="col" style="color: green;">'.$status.'</th>';
else if ( $status == 'PEN' )
    echo '<th width="4%" scope="col" style="color: red;">'.$status.'</th>';
else if ( $status == 'ART' )
    echo '<th width="4%" scope="col" style="color: blue;">'.$status.'</th>';

?>

Inline editing

echo '<th width="4%" scope="col" ';

if ( $status == 'PG' )
    echo 'style="color: green;"';
else if ( $status == 'PEN' )
    echo 'style="color: red;"';
else if ( $status == 'ART' )
    echo 'style="color: blue;"';

echo '>'.$status.'</th>';

I think your are trying to set background color on based of $status...try this.

<?php 
If($status=='pg'){
      $color='red';
 }
elseif($status=='pen')
{
     $color='green';
}
elseif($status=='atr')
{
      $color='yellow';
 }
?>
<th width="4%" scope="col" style="background-color:<?php echo $color;?>">
    <?php echo $status;?>
</th>