Modulus in a PHP loop

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.

for($i=1; $i <= $count; $i++)
    if($i % 2 == 0) echo 'This number is even as it is divisible by 2 with no leftovers! Horray!';

Leave a Comment