All major programming languages have it, it’s the modulo operator, and it has multiple uses. First I’m going to explain what it is, then I’m going to demonstrate one very simple, very powerful use.

Programatically, the modulo operator is most commonly denoted with a percentage ‘%’ symbol. Given two numbers as input, the modulo operator returns the remainder after division. p = a%b; will return the remainder after a is divided by b.

Here are some examples:

** **

2%2 = 0 (2 divided by 2 = 1 remainder 0)

6%2 = 0 (6 divided by 2 = 3 remainder 0)

7%2 = 1 (7 divided by 2 = 3 remainder 1)

18%4 = 2 (18 divided by 4 = 4 remainder 2)

** **

The modulo operator is used extensively in cryptography, Diffie-Hellman (DH) Key Exchange is just one example.

As a PHP Programmer, what can this be useful for?

Take a look at the alternative shading on the bottom right hand side of this page under the “Widgets and Links” area. The list of links is taken, and this shading whereby every alternative link is a different color using the modulo operator. Here’s how, using semi PHP pseudo-code:

$num = NUMBER_OF_LINKS; $ctr = 0; while ($ctr < $num) { if ($ctr%2) { echo â€˜<div style=â€background-color:#SHADED..â€>â€™; //shaded background } else { echo â€˜<div>â€™; //regular background } //link and description goes here </div> $ctr++; }

The important line is if ($ctr%2). On each iteration of this loop, $ctr is incremented by 1. 0%2 = 0, 1%2= 1, 2%2 = 0, 3%2 = 1, etc.. This ‘if’ will switch between true and false for each other iteration.