Treehouse: Grow your CSS skills. Land your dream job.

Last updated on:

Insert Element Every nth Loop

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:

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

Comments

  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:

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