| Tutorials Main Latest Tutorials Popular Tutorials Top Rated Tutorials |
| Login to See your Favorite Tutorials |
| 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) | |
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> |
| 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>"); } ?> |
| Code: |
| $row_class = empty($row_class)? "alt" : ""; |