Understanding How the Modulus Operator Works

I've used the modulus operator in PHP for a while, but I didn't truly understand how it works. Now, I know how to divide. I also know that the modulus operator returns the remainder when one number is divided by another. However, my calculation just didn't match the returned result. So let's look at where I went wrong.

How It Works

Last week's post (Build HTML Tables Dynamically with PHP Part 3: CSS Alternative), dynamically added a class attribute to every third column. This allowed us to simulate an HTML table and display pictures in rows of three. The following line of code was used to do that:

$classAttr = ($i%3) ? '' : ' class="clearFloat"';

Basically, that adds the class attribute to every column where the column counter ($i) is evenly divisible by three. To help understand how the modulus operator works, let's create a quick loop to display the modulus operator's output.

<?php
//INITIALIZE VARIABLES
$testValues = range(1, 15);
$numValues  = count($testValues);
 
//SHOW MODULUS OUTPUT
for($i=0; $i<=$numValues; $i++) {      print "<div>$i % 3 = " . ($i%3) . '</div>'; } ?>

The results from the loop are as follows:

0  % 3 = 0
1  % 3 = 1
2  % 3 = 2
3  % 3 = 0
4  % 3 = 1
5  % 3 = 2
6  % 3 = 0
7  % 3 = 1
8  % 3 = 2
9  % 3 = 0
10 % 3 = 1
11 % 3 = 2
12 % 3 = 0
13 % 3 = 1
14 % 3 = 2
15 % 3 = 0

Note that every time a number is evenly divisible by three, the modulus operator returns 0...or no remainder. When the value is 0, last week's code adds the class attribute.

Conclusion

The output looks good and we get the desired rows of three. However, I couldn't figure out where those ones and twos were coming from. In my calculations, 7 / 3 = 2.333 and .333 doesn't equal 1. Apparently, I just needed go back to fourth grade math and learn how to calculate the remainder.

0 Comments

There are currently no comments.

Leave a Comment