How to alternate table row colours the easy way

September 11, 2009 by Adam · Leave a Comment 

We’ve all seen the familiar code in our baked index files:

<?php
$i = 0;
foreach ($pricings as $pricing):
	$class = null;
	if ($i++ % 2 == 0) {
		$class = ' class="altrow"';
	}
?>
<tr <?php echo $class; ?>>


I’ve always thought that this wasn’t quite as elegant as it should be, and certainly not very DRY, as it was required everywhere you wanted alternate row colours. Well today I came across this nice little CakePHP helper by @markgandolfo for alternating table colours in a very similar way to Rails, which takes the above code and makes it look more like this:

<table>
	<?php foreach($items as $item): ?>
	<tr class="<?php echo $cycle->css(); ?>">
		<td><?php echo $item; ?></td>
	</tr>
	<?php endforeach; ?>
</table>


Much better.

Check it out here: http://github.com/markgandolfo/cakephp_cycle_css/tree/master