I feel just a wee bit lazy sharing this, because this snippet is only five lines long. However, these five lines have done more to make one of my sites pleasant to read than just about any other five lines of PHP I've written.
The idea: let PHP drop in alternating styles into your comment text. On skins 2 and 3 of geek-chick.net I use this to alternate the colors of table rows, but in this example I'm showing you how to use it in a <p> tag.
This should be a quickie to implement, no matter what CMS you're using.
Put this block of code up at the top of your page:
<?
function comment_style() {
static $comment_count;
$comment_count++;
if ($comment_count % 2) {
echo "odd";
}
else {
echo "even";
}
}
?>
…and for whatever bit of repeating text that you want to alternate styles on (usually comments), do this:
<p class="<? comment_style(); ?>">
I've set up the classes "odd" and "even" in my stylesheets. If you want different names, change them in the comment_style() function and name them appropriately in your style sheet.
What does this function do? Pretty simple, really. It declares the variable $comment_count to be static, meaning that the current value of $comment_count isn't erased after each time the function runs. (Otherwise, it would run, and reset, and run, and reset, and $comment_count would always be equal to 1…which is useless.)
Here's the part that might snag you. $comment_count % 2 doesn't mean "divided by two." Division, in PHP, is done by the / operator. That next line actually means "If the current value of $comment_count, divided by two, generates a remainder, then echo "odd."
Those wacky coders….
I'm sure there are vastly more interesting uses for this code than what I've come up with so far, so I thought I'd share with you guys.