|
Alternating Row Colors in HTML Tables Using PHP
We've all run into a situation where we have a good bit of data
comprising a number of rows and wished there was a nice easy
way to make the rows display using alternating colors. That's
what this tutorial will do. You'd be surprised at how easy it
really is.
For the purposes of this tutorial, we're going to use the
following array as our data source to fill the tables.
$myArray = array("Dave","Bill","Brian","Mike","Jason","Eric","Phil","Ben","Chris","Larry");
This is going to be a simple example, but there's really no
difference between having a single column vs. having multiple
columns of data.
The next thing we need is a couter to keep track of the row
number we are on. We'll use $i and initialize it to
'1' outside of our loop.
Next we need to create a variable to hold the current row color.
We'll use $rowColor. That's about it for the variables
we're going to need, so let's start building our code.
<?php
$myArray = array("Dave","Bill","Brian","Mike","Jason","Eric","Phil","Ben","Chris","Larry"); # Our table fill data
$i = 1; # Our row counter
?>
<p>Here's our table with alternating row colors. The second column is the row
number for your reference.</p>
<table align="left" width="25%" cellpadding="3" cellspacing="0">
<?php
foreach ($myArray as $row)
{
if ($i % 2 != 0) # An odd row
$rowColor = "green";
else # An even row
$rowColor = "orange";
echo '<tr bgcolor="' . $rowColor . '"><td align="left"><font color="white"><b>' . $row . '</b></font></td><td align="right"><font color="white"><b>' . $i . '</b></font></td></tr>' . "\r\n";
$i++; # Increment our row counter
}
?>
</table>
Here's our table with alternating row colors. The second column is the row
number for your reference.
| Dave | 1 |
| Bill | 2 |
| Brian | 3 |
| Mike | 4 |
| Jason | 5 |
| Eric | 6 |
| Phil | 7 |
| Ben | 8 |
| Chris | 9 |
| Larry | 10 |
|