Stripey tables using CSS and PHP
4
I like it when alternate rows in a table are formatted differently - it makes it easier to scan your eyes along a row without losing which row you’re actually reading. The rows don’t have to be vastly different (at least not for someone with semi-decent eyesight) and a good example of this is iTunes:

There’s an article titled Zebra Tables on A List Apart which tells us how to achieve this effect using JavaScript - perfect, but I prefer to do it a different way.
I found a PHP script on scriptygoddess for formatting alternate comments and thought I could adapt it for table use - on re-reading the article it seems this was the script’s original function anyway.
First off, we have the script itself (which is put in the <head> of the page):
<?
$tablerow_count=0;
function tablerowswitch() {
global $tablerow_count;
$tablerow_count++;
if ($tablerow_count % 2) {
echo "odd";
}
else {
echo "even";
}
}
?>
I can’t explain exactly what does what (my knowledge of PHP is limited at best), but I get the general idea: increment tablerow_count by one and if it then leaves a remainder when divided by 2, output odd, otherwise output even.
Now, in the table itself we need to call the function tablerowswitch each time we create a new row, so the table looks like:
<table summary="My rating for tracks on Orbital's Blue Album">
<thead>
<tr>
<th>Song name</th>
<th>My rating</th></tr>
</thead>
<tbody>
<tr class="<? tablerowswitch(); ?>">
<td>Transient</td>
<td><img src="4stars.gif" /></td>
</tr>
<tr class="<? tablerowswitch(); ?>">
<td>Pants</td>
<td><img src="4stars.gif" /></td>
</tr>
</tbody>
</table>
And the CSS:
tr.even { background-color:#e8e8ff; }
All of this together gives us (me) the desired effect, which can be seen in this example … with one small problem: what if I have two separate tables on a page and the first one has an odd number of rows? This’ll cause the second table to look slightly odd as it’s first row will be class="even". This isn’t a great loss, but it annoys my anally retentive side. So, we need to put:
<? $tablerow_count=0; ?>
in the <thead> of each table to reset tablerow_count to zero.
Super.
Ahh, a fellow PHP developer.
Ever tried fooling around with Smarty templates? (go to: http://smarty.php.net/manual/en/ )
And by way of something utterly unrelated: pictures of insects. (go to: http://www.bugdreams.com/ ) - Wayne Smallman
I wouldn’t use the term "developer", more like "bloke who knows enough to just get by".
Smarty templates looks good but also way too fancy for my needs - Movable Type is too much for my needs as it is!
Nice bug pictures - good use of colours. - Timmargh
I’ve been tapping away [mostly happily] in PHP for about three and a bit years.
I’m currently working on .. oh, nearly forgot, I can’t tell you! - Wayne Smallman
Ooh, you tease! - Timmargh
Comments