Ashley Sheridan​.co.uk

Alternate Table Rows in PHP

Posted on

I often see people asking around on forums and mailing lists, how best to create tables with alternate rows, and I often see a variety of methods, many of which are quite frankly scary! Sure, CSS3 has a pretty nifty solution in the form of the nth-child selector, but this has limited browser support (currently, it is not recognised by Firefox 2 & 3 or IE 6 & 7), and CSS3 has not yet been fully ratified.

One common solution is to use Javascript, which is, I feel, the wrong answer. The drawback with this approach, is that should the UA not support Javascript, or have it disabled, the rows are not coloured.

Ideally, CSS should be used, and applied as a class per row as required, and the best way is to have them programatically inserted by server-side code:

<table> <?php $rows = 10; for($i=1; $i<=$rows; $i++) { $rowClass=($i % 2 == 0)?'class="alternate"':''; print "<tr $rowClass><td>row: $i</td></tr>"; } ?> </table>

Line 6 uses the ternary operator of PHP, which is essentially a short if statement. Take care with the use of quotation marks here. The outermost for each statement on this line are single quotation marks, while the innermost that enclose the word 'alternate' are double. This is just because I prefer all my HTML code to use double quotes for parameter values.

And that's it. You only need to apply one class because the other rows will inherit the default for that table. Then you could use CSS that looks something like this:

tr { background-color: #f6f1e0 } tr.alternate { background-color: #d6efe5 }

This will give you a table that is guaranteed to work in every CSS capable browser, as all the actual work is done server-side.