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;
	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.

  • I guess $i will take values 0 or 1 which is little limiting as to the naming of the classes.

    I use:
    ($i%2 == 0)?$class=’white_class’:$class=’green_class’;
    <div class="”>….

    which is a bit longer but gives you more freedom in choosing the names of the classes. For example you can easily change green_class to light_green_class without having to modify your original green_class.

    • @VangelisB, you are totally right. Thanks for your input! 🙂

  • Pingback: Alternate row colors with pure CSS, yes, CSS3 | Danny Herran()