A simple piece of code to do a simple operation - alternate background color of table rows.

If you are displaying a large amount of data within a table, a nice formating touch is to change the background of each alternate table row.

1
2
3
3
4
5

To do this, you simply need to check what row you are on. To do this we use the remainder operator %. For odd and even row coloring, check for a value in $rownumber%2. For every third row use $rownumber%3 and so on. Once you know which row you are on, set the background style accordingly. You could even define custom styles for each remainder value.

<?php 
$numrows     = 30;
$changestyle = 2;
print("<table>");

for($i=0;$i<$numrows;$i++)
{
    print("<tr ".(!($i%$changestyle)?"style=\"background-color:#afafaf;\"":"").
            "><td> $i </td></tr>");
}

print("</table>");
?>