DCR DCR - 1 year ago 84
HTML Question

How to color table cell based on content

I"m using the following php code to color different cells in my html table but was wondering if there was a better way of doing this.

<?php if($crew['status'] == 'OUT') { ?>
<td style='text-align:center;font-size:80%;color:red' ><?php echo $crew['status'] ?></td>
<?php } else if($crew['status'] == 'OPEN') { ?>
<td style='text-align:center;font-size:80%;color:blue' ><?php echo $crew['status'] ?></td>
<?php } else if($crew['status'] == 'CONFIRMED') { ?>
<td style='text-align:center;font-size:80%;color:green' ><?php echo $crew['status'] ?></td>
<?php } else if($crew['status'] == 'WAITLIST') { ?>
<td style='text-align:center;font-size:80%;color:purple'><?php echo $crew['status'] ?></td>
<?php } else { ?>
<td style='text-align:center;font-size:80%;color:orange'>TIMESPAN</td>
<?php } ?>

Answer Source

Plenty... You should avoid using lots of inline CSS.

You could do something like the following:

#yourtable tr td {

$colors = [
  'OUT' => 'red',
  'OPEN' => 'blue',
  'CONFIRMED' => 'green',
  'WAITLIST' => 'purple'

<?php if (array_key_exists($crew['status'], $colors)): ?>
<td style="color:<?= $colors[$crew['status']]?>"><?= $crew['status'] ?></td>
<?php else: ?>
<td style="color:orange">TIMESPAN</td>
<?php endif ?>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download