DCR DCR - 6 months ago 27
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

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

You could do something like the following:

<style>
#yourtable tr td {
  text-align:center;
  font-size:80%;
}
</style>

<?php 
$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 ?>