The Lodge is members-only design/dev videos and Office Hours.

Next Office Hours Session: "Programming Fundamentals" Dec 02 - 2:00 PM Eastern

Insert Element Every nth Loop

Last updated on:

When inside of a loop, you can keep track of the iteration number of the loop (shown below is a simple for loop). Using that iteration number, you can calculate it's modulus of some number (number left over after an even division). If that modulus is zero, you are at an even division of whatever that number was.

So in this simple loop below, it will output something every third time through the loop:

   for ($counter = 1; $counter < 100; $counter++ ) {
     if ($counter % 3 == 0) {
            echo "<p>Every third!</p>";


  1. Jack
    Permalink to comment#

    I had no idea you could do this! There’s me doing if(float/3 == round(float/3)){!

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in in triple backtick fences like this:

  function example() {
    element.innerHTML = "<div>code</div>";

There's a whole bunch of content on CSS-Tricks.

Search for Stuff   •   Browse the Archives

Get the Newsletter ... or get the RSS feed