I ran across this code in the index.php file of Alexander Agnarson’s fantastic free Wordpress theme Hueman
and couldn’t figure out what it did:
<?php if($i % 2 == 0) { echo '</div><div class="post-row">'; } $i++; endwhile; echo '</div>'; ?>
Specifically, the part with the % sign:
($i % 2 == 0)
After some searching, I discovered that the percent sign was also known as the modulus operator, which works like this:
<?php $a % $b // Displays the REMAINDER after $a is divided by $b // Examples 6 % 2 = 0 // 6 is divided by 2 three times with 0 remaining 5 % 2 = 1 // 5 is divided by 2 two times with 1 remaining 4 % 2 = 0 // etc.. 3 % 2 = 1 2 % 2 = 0 1 % 2 = 1 0 % 2 = 0 ?>
In the theme, this code helps form the 2-across grid layout displaying blog posts on the homepage:
<?php if($i % 2 == 0) { echo '</div><div class="post-row">'; } $i++; endwhile; echo '</div>'; ?>
In other words, $i
serves as the number of blog posts cycling through the query loop. Everytime that number of posts equals a group of 2 (resulting in nothing left over, i.e. == 0
), the code wraps the pair in closing and opening div
tags.
Pretty neat!
Other resources:
Khan Acadmeny – What is Modular Arithmetic?