Categories: Development

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

 

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago