PHP: How do you determine every Nth iteration of a loop? PHP: How do you determine every Nth iteration of a loop? php php

PHP: How do you determine every Nth iteration of a loop?


The easiest way is to use the modulus division operator.

if ($counter % 3 == 0) {   echo 'image file';}

How this works:Modulus division returns the remainder. The remainder is always equal to 0 when you are at an even multiple.

There is one catch: 0 % 3 is equal to 0. This could result in unexpected results if your counter starts at 0.


Going off of @Powerlord's answer,

"There is one catch: 0 % 3 is equal to 0. This could result in unexpected results if your counter starts at 0."

You can still start your counter at 0 (arrays, querys), but offset it

if (($counter + 1) % 3 == 0) {  echo 'image file';}


Use the modulo arithmetic operation found here in the PHP manual.

e.g.

$x = 3;for($i=0; $i<10; $i++){    if($i % $x == 0)    {        // display image    }}

For a more detailed understanding of modulus calculations, click here.