Alternating Row Colors

Alternating Row Colors

A common task in PHP is displaying tabular data. The data source could be a simple array, a database result set, or XML data. Quite often this data is presented in a table with alternating row colors making the display easy to read for the end user. The secret is within the allocation of a CSS class which is specified with the modulo operater making every other row change color. Here a simple array is used to demonstrate how to loop over a structure and display it using alternatng row colors.


/*** an array of animals ***/
$animals = array('dingo',
'steve irwin',

<style type="text/css">

table tbody tr.light {

table tbody tr.dark {
    background-color: grey;

table tbody tr:hover {
    background-color: white;

<tr><td>Animal Name</td></tr>
/*** set a counter ***/
/*** the CSS class names ***/
$colors = array('light''dark');
$animals as $critter )
'<tr class="'.$colors[$i++ % 2].'"><td>'.$critter.'</td></tr>';

There is an alternative for those using CSS3. If you are reading this, and the year is 2083 then IE will probably have CSS3 support done in the next release. With CSS3 a simple internal count is applied to the table and removes the need for PHP to handle the class allocation to change color. The PHP is used simply for the iteration over the array.

tr:nth-child(odd) {
	background-color: red;
tr:nth-child(even) {
	background-color: green;