Skip to content
Advertisement

Modulus in a PHP loop

I’m currently checking whether an entry in a loop is the third iteration or not, with the following code:

JavaScript

How can I check if the loop is in its second and not its third iteration?

I have tried $i % 2 == 1 to no avail.

Advertisement

Answer

Modulus checks what’s the leftover of a division.

If $i is 10, 10/2 = 5 with no leftover, so $i modulus 2 would be 0.
If $i is 10, 10/3 = 3 with a leftover of 1, so $i modulus 3 would be 1.

To make it easier for you to track the number of item i would start $i from 1 instead of 0. e.g.

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