Skip to content
Advertisement

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

I wanted to echo an image every after 3 post via XML here is my code :

JavaScript

here is a sample first 3 are correct but now it doesn’t loop idgc.ca/web-design-samples-testing.php

Advertisement

Answer

The easiest way is to use the modulus division operator.

JavaScript

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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement