Many people ask how you can alternate row colours in a table  when using multiple rows. The answer is simply to check whether the row loop is an even number or not using the modular symbol (%). In this case we’ll use PHP.

<table>

<?

for ($i = 0; $<50;$i++) {

if ($i % 2 == 0) {    echo ‘<tr bgcolor=”#f0e8f2″>’; } else { echo ‘<tr>’; } ?>

<td>my column</td>

</tr>

} ?>

</table>

This makes 50 rows and the command ($i % 2 ==0) asks if the variable is even and if so colour the background of the row. This technique becomes very handy when we don’t know exactly how many rows we are displaying. For example when loading in multiple rows from a database. The following example loads rows in from a mysql database. This code presumes you’re already connected to the database.

<?

$sql= “SELECT * FROM items”;

$result = mysql_query($sql) or die (mysql_error());

$i = 0;?>

<table>

<?
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){

if ($i++ % 2 == 0) {    echo ‘<tr bgcolor=”#f0e8f2″>’; } else { echo ‘<tr>’; } ?>

<td> <? $row['id']; ?> </td>

<td <? $row['name']; ?> </td>

</tr>

<? } ?>

</table>

Notice the slight change of code: if ($i++ % 2…

The variable $i is incremented (increased by one) automatically each loop. If you need to change the starting colour then simply change the 0 to a 1 so it asks if the number is odd.

Leave a Reply

You must be logged in to post a comment.