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"' : ''; ?>

View this post on Github

You might also enjoy…

Mike Street

Written by Mike Street

Mike is a CTO and Lead Developer from Brighton, UK. He spends his time writing, cycling and coding. You can find Mike on Mastodon.