Monday, 2 February 2015

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.

<?php
/*** an array of animals ***/$animals = array('dingo',
        
'wombat',
        
'platypus',
        
'kangaroo',
        
'steve irwin',
        
'wallaby',
        
'kookaburra',
        
'kiwi');?>
<html>
<head>
<style type="text/css">

table tbody tr.light {
    background-color:pink;
}

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

table tbody tr:hover {
    background-color: white;
}
</style>
</head>

<body>
<table>
<thead>
<tr><td>Animal Name</td></tr>
</thead>
<tfoot>
<tr><td>PHPRO.ORG<td></tr>
</tfoot>
<tbody>
<?php
    
/*** set a counter ***/
    
$i=0;
    
/*** the CSS class names ***/
    
$colors = array('light''dark');
    foreach( 
$animals as $critter )
    {
        echo 
'<tr class="'.$colors[$i++ % 2].'"><td>'.$critter.'</td></tr>';
    }
?></tbody>
</table>
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;
}

0 comments:

Post a Comment