Clan Adverts

PHP Web Host - Quality Web Hosting For All PHP Applications

 

Alternating row classes in PHP, easy style

Description: Learn how to alternate row classes in PHP
Version: 1.0
Added on: 01 July 2007
Author: ped
Difficulty Level: Intermediate
Views: 3306
Rating: 7.0 (1 Vote)
Detailed ProfileView Comments (1)

Ok. I have seen a myriad of techniques on creating the PHP code to pump out alternating row classes on tables, list elements, what have you. It’s usually some counter variable that you divide by 2 to see if there is an even result (MOD operator). But then you got the whole initialize the variable, increment the variable, test the variable scenario. Blegh.

I’ve also seen some crazy technique using bitwise & operators, which is hardly readable for common folk, but I do admit is probably blazing fast. Only issue there, once again, you are maintaining a counter variable and incrementing it. Blegh.

I do not claim for this method to be better. I simply claim that this is my method and I use it. Take it as you will.

First, lets set up a style:

Code:
<style>
tr.alt td{
background-color:#D5E0E1;
}
</style>


Done...

Next, the PHP code intermingled with some HTML

Code:
<?php
for($i = 0; $i < 10; ++$i){
   $row_class = empty($row_class)? "alt" : "";
   echo("
      <tr class=\"$row_class\">
         <td>
            data 1
         </td>
         <td>
            data 2
         </td>
         <td>
            data 3
         </td>
   </tr>");
}
?>


The key for the alternating row classes of course, lies in one line of PHP code:

Code:
$row_class = empty($row_class)? "alt" : "";


I’m using PHP shorthand to do an if statement and check if the variable $row_class is empty or a blank string (”"). If it is then I set it to “alt”. As you can imagine, next row, the same statement is ran. This time, it’s not empty, so it gets set to empty, thus alternating between the “alt” class and empty.

Tutorials ©