Zebra Striping with PHP the Easy Way

Chris Sedlmayr

16 Mar 2010

Using one of the built in Maths functions of PHP we can easily create zebra striped lists.
Let’s say we have an array of entries stored within the $comments variable.
All we have to do with this is to use the fmod function and assign a css class that alternates per entry.

    <?php foreach ($comments as $int => $comment): ?>
        <li class="<?php echo fmod($int, 2) ? 'even' : 'odd' ?>">
    <?php endforeach; ?>

Then just give the even and odd classes different colours to suit your layout.

li.even {

li.odd {

And you’re done!