So what exactly happened here? Well, we used a mathmatical
function called Modulus which performs division but
instead of returning the result of the division it returns the
remainder. So 1 % 1 returns '0' because there is no
remainder. 1 % 2 returns '5', 2 % 2 returns '0',
3 % 2 returns '5', 4 % 2 returns '0', etc. Since
any even number will be evenly divisible by '2', the even rows
will always fall in the else portion of our if
In our code we used an if statement to test if the
returned value was not equal to '0' and assigned one color to
that condition, and assigned a different color if it was.
if ($i % 2 != "0") # An odd row
$rowColor = "green";
else # An even row
$rowColor = "orange";
Well, that's how you do it. Pretty simple huh?
An even simpler way for just two alternating row colors:
The first example works great if you have more than just two
row colors you want to use. For instance, if you wanted to do
three row colors, you would just add another color and do a
modulous by 3. If you only want to alternate back and forth
between two row colors, you can get rid of the math modulus
We're going to use the same array of names we used as the data
in the first example, but now we're going to add another array
to hold our two row colors.
$bgcolor = array(0=>"seagreen",1=>"slateblue");
Next we'll use $a as our counter for alternating row colors.
What we're going to be doing with $a is notting it. This means
it'll flip back and forth between false (technically a zero) and
one, which conveniently, is the array elements we used in our
$bgcolor array. Here's the code which is very similar
to the first example except $bgcolor[$a] and $a = !$a.
The second column is the value of $a for your reference.
foreach ($myArray as $row)
echo '<tr bgcolor="' . $bgcolor[$a] . '"><td align="left">
<font color="white"><b>' . $row . '</b></font></td>
<td align="right"><font color="white"><b>' . $a . '</b>
</font></td></tr>' . "\r\n";
$a = !$a; # flip the bit