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. 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

  • Use Markdown, and it will escape the code for you, like `<div class="cool">`.
  • Use triple-backticks for blocks of code.
    ``` 
    <div>
      <h1>multi-line block of code</h1>
      <span>be cool yo.</span>
    </div>
    ```
  • Otherwise, escape your code, like <code>&lt;div class="cool"&gt;</code>. Markdown is just easier though.

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".