The modulo operator

Out of all operators in programming, it is the modulo operator that goes under the radar most. Perhaps this is due to a lack of need or even an understanding of how it works and when to use it.

In the simplest terms, modulo operator is the remainder from a division of one number by another. Compare this to a simple division which is the times the number goes into the other.

Examples

Here are some examples in PHP

echo (20 % 12);//8

The answer is 8 because 12 goes into 20 once and 8 is left over.

echo (40 % 12);//4

12 goes into 40 three times (36) and 4 is the remainder.

Checking if a number is odd or even with the modulo operator:

if ($number % 2 == 0) {
    echo "Even";
} else {
    echo "Odd";
}

This works because 2 will always go into an even number and have 0 remaining.

Another great use for the modulo operator is running a loop and getting every tenth, hundred, thousandth etc;

for ($i = 1; $i <= 100000; $i++) {
    if ($i % 5000 == 0) {
        echo $i.'<br>';
    }
}

Outputs

5000
10000
15000
20000
25000
30000
35000
40000
45000
50000
55000
60000
65000
70000
75000
80000
85000
90000
95000
100000

Whilst

for ($i = 1; $i <= 50000; $i++) {
    if ($i % 1500 == 0) {
        echo $i.'<br>';
    }
}

outputs

1500
3000
4500
6000
7500
9000
10500
12000
13500
15000
16500
18000
19500
21000
22500
24000
25500
27000
28500
30000
31500
33000
34500
36000
37500
39000
40500
42000
43500
45000
46500
48000
49500