biscuit

Alternating PHP Loops with Modulus

A fairly simple operator in PHP is modulus (%), which allows you calculate the remainder of one integer when divided by another.

You may ask why this is important in programming? The reason is that when used within loops it allows us to create actions for when certain values are met. For example, we could write a condition that every time we get a value that is a multiple of 4 (remainder of 0), add a class.

Scenario

I recently wrote a blog post which shows how to list the direct subcategories of a category in Magento (read it here). When put into practice you’ll find that in order to have certain elements in the loop sit flush to the sides of the container (without margin) then the final iteration on each row needs a margin of 0. This for example could be every 3rd iteration.

This is where modulus would come into play. Read below to see how to inject this into your loops. I’ve written this in PHP as it’s my preferred language, but the same logic applies in most programming languages.

Example

First of all let’s make an array to play with:

$biscuits = array(
			"custard cream", 
			"rich tea",
			"cookie",
			"oreo",
			"bourbon",
			"jammie dodger",
			"digestive",
			"shortbread",
			"party ring");

Hungry yet? Now I’ll demonstrate modulus with two types of loops:

For Loop

This will add the ‘no-margin’ class to every 4th iteration:

for ($i=1; $i<count($biscuits); $i++)
{
	echo '<li'.($i % 4 == 0 ? ' class="no-margin"' : '').'>'.$biscuits[$i].'</li>';
}

Which results in:

<li>rich tea</li>
<li>cookie</li>
<li>oreo</li>
<li class="no-margin">bourbon</li>
<li>jammie dodger</li>
<li>digestive</li>
<li>shortbread</li>
<li class="no-margin">party rings</li>

Foreach Loop

This will add the ‘no-margin’ class to every 2nd iteration:

$i = 1;
foreach ($biscuits as $biscuit)
{
	echo '<li'.($i % 2 == 0 ? ' class="no-margin"' : '').'>'.$biscuit.'</li>';
	$i++;
}

Which results in:

<li>rich tea</li>
<li class="no-margin">cookie</li>
<li>oreo</li>
<li class="no-margin">bourbon</li>
<li>jammie dodger</li>
<li class="no-margin">digestive</li>
<li>shortbread</li>
<li class="no-margin">party rings</li>

What’s Happening?

For those new to PHP, I’ll just explain what’s happening. The important code is this part:

($i % 2 == 0 ? ' class="no-margin"' : '')

This is a shorthand if statement which is basically saying “if this row iteration is divisible by 2 (a multiple of 2) without remainder then echo this string”. As long as you have an $i iterator in your loop and the code above you’ll be winning.

For more information about ternary operators and shorthand PHP, this blog is a great place to start.

  • http://www.homegardenandconservatory.co.uk Gillian

    Can I use this to make my subcategory listing appear as a grid in Magento?