Add Element Every nth Loop Using the PHP Modulus Arithmetic Operator

Add Element Every nth Loop Using the PHP Modulus Arithmetic Operator

Posted by Rainey

When laying out dynamic elements on a page, it can be handy to insert an element before or after every nth element. A simple way to achieve this is using the Modulus Arithmetic Operator. Modulus basically returns the remainder of a number divided by another. So, for example:

  • 9/3=3 with no remainder, so 9 % 3 is 0.
  • Or, 9/4=2 with 1 remaining, so 9 % 4 is 1.

With this in mind we can create a quick way to know when we are on nth number.

Here is a quick example in action:

<?php
  for ($count = 1; $count < 50; $count++ )
     if ($count % 5 == 0){ 
         echo '<div>I found the Fifth Element!</div>'; // Good Movie
     } 
  }
?>

Here we are setting the first loop count to one and running the loop until the count hits 50. By detecting when the modulus leaves no remainder or is 0, we can know we are on the 5th element.

An example of this in practice:

  <?php
    if ( have_posts() ) {
        $count=0; // Establish count outside loop
 		while ( have_posts() ) {
                    $count++ // count loops
                    <div class="four columns">
 			the_post();
                      </div>
                     // add hr after every 4th element
                     if ($count % 4 == 0){ echo '<hr class="row">; }
 		} // end while
 	} // end if
  ?>

Here I have a typical WordPress loop using a sixteen column grid layout. In this situation I need to know when I hit the 4th element so that I can add a hr tag to clear those divs. Otherwise I could end up with one taller div that causes the next row to look very odd.  Obviously, Modulus can have many other applications, but this is one I find I need pretty regularly.  Do you have other interesting applications for this?  If you do, please share in the comments.

Like what you are reading? Subscribe to receive monthly tips & updates!

A Monthly Roundup of Articles and a Sweet Deal

Get the latest tips, tricks, tutorials and freebies in your inbox once a monthly.

Join our growing community of front-end web developers and designers. We are constantly publishing new industry tips, tricks and tutorials to help you take your game to the next level. We are also going to include a freebie or deal on something cool each month. Enter your email below and you will only receive this email once a month, nothing else.

Subscribe to our mailing list

* indicates required


    Today in Web Design - PHP, Tutorials
    Tagged | ,