Alternate row colors with PHP

Posted by Danny Herran on Aug 10, 2010 in Backend | 3 comments

I know there are several ways to accomplish this, however, of all the ones I’ve tried, this is the shortest so far:

$i = 0;
while(true)
{
	echo '<tr, td, div, row, whatever, here class="row'.$i.'">';
	$i = 1 - $i;
}

So, if you make two classes, row1 and row2, each with a different background color, the result will be alternated row colors in whatever you’re doing. Very useful for long lists.

Update: you might be interested in how to alternate row colors with pure CSS.