Get an 'Even' Class

This  PHP statement applies class="even" to every other element when in a loop.

Since this post was originally created, CSS has somewhat evolved, allowing you to do div:nth-child(even) to style every other element

I often use this on tables to get an even class to help divide up the rows, but it can also be used to add a class to the 4th item in a list (if you want to remove certain margin/padding for example).

To start, 'clear' $i and make it equal to 0. (if $i is already used elsewhere in your code, you can replace it with anything)

$i = 0;

Then once in the loop, use/adapt the following code to achieve the desired result (have broken it up into separate lines to add comments. The single line code is included after)

<?php
echo $i++ % 2 ? // if $i divided by 2 has no remainder
' class="even"' : // then echo this result
''; // if not echo this result

the number 2 can be replaced with what ever number item you want the class. And if you already have existing classes on your item, then remove the class="" and just have the class name.

The code as a single line:

<?php echo $i++ % 2 ? ' class="even"' : ''; ?>
This website is currently having a full content audit - apologies if some of the code or content looks a bit funky!

View this post on Gitlab

You might also enjoy…

  • Redirect to one central domain - htaccess

    Posted on 21st February 2011.

    If you would like to 'redirect' all your users to a central domain (for example if you would like all users to browse your site with the www or you have several parked domains)

  • Giving something a 'Last' Class

    Posted on 14th February 2011.

    If you want to apply a different class to the last item in a list generated by PHP, start off with Setting the $lastOne variable to the end of your list

Mike Street

Written by Mike Street

Mike is a front-end developer from Brighton, UK. He spends his time writing, cycling and coding. You can find Mike on Twitter.