# Understand PHP Modulo: Tricks with Division Remainders

When I learned math, I didn’t really understand the modulus function. In fact, it was until I learned PHP that I understood the value of a remainder from division. PHP’s role in making websites makes the modulus operator (or modulo) much more important than it ever was in math class for me.

In this article, we’ll cover the PHP modulo operator, the mathematics behind it, and why using it for things like finding every 4th item and more are just so darn useful when you’re aiming to make great web pages.

## The Core Concept: What Modular Division Means

When I was in school (I do imagine it’s different now) we learned division via a many-step process. I won’t bother to explain it in text, but sometime division is round: we know that 21/3 = 7. And sometimes it’s not. 22/3 = 7.???????. That’s how this whole “modulus”, “modulo”, or “modular division” comes to be a little important if you’re doing PHP.

Mod in PHP is useful become sometimes it’s *very* useful to know that the “remainder” when you divide 22 by 3 is one. Which is to say that you can clearly get at least 7 out of dividing 22 by 3, and that one “uneven” bit remains after you’ve done this.

This is useful for a few reasons. First because you may know off-hand (that is: without having to think hard) that 1/3 is expressed decimally as .33333. So I know that 22/3 = 7.33333. Because I know that 7 fits cleanly, and that I could express the **remainder** of my division cleanly as 1, or 1/3 = **0.33333**.

## What PHP Modulo Does For Us

So, these remainders. They matter a little more than just the ability to more easily find decimal fractions of numbers. How else do they matter? Primarily in that we’re able to consistently know that we have the “second of every three” items simply from knowing the remainder of dividing.

What does this allow us to do? It always us to use a PHP remainder function to cleanly label a whole set of things (say `div`

s on a webpage) as being the “first of three”, “second of three,” and “third of three.”

I’m getting a bit ahead of myself though. First let’s make sure we understand how we write out a PHP modulo operation. Then we can get into what knowing the remainder unlocks for us in our PHP code.

### Basic Calculation in using the Modulus Operator in PHP

So, I’ve told you about this magic “get the remainder” PHP functionality. It’s one of PHP’s many arithmetic operations. How do you use it? I won’t belabor it too long. Here’s how you get the remainder we discussed above for dividing 22 by 3:

```
$remainder = 22 % 3; // 1
```

If you didn’t catch it look again. That’s not the division symbol `/`

of PHP math. For better or worse, it’s the percent `%`

symbol. That’s the operator you need for modulo in PHP.

So like I said before, what’s powerful about the modulus operator (the humble `%`

) is that it lets us reliably get however many values we use as the divisor, *in any situation.* So, if I have a line like this:

```
$is_odd = $i / 2;
```

This PHP code works to find if a number is odd. Determining odd or even in PHP code is that simple. More accurately, it’s simple if you understand the modulo operator. Which hopefully you’re well on your way to.

Technically, this works because PHP does type juggling. When I divide an *even* numbers by 2, there is never any remainder. So `$is_odd`

would be `0`

for a number like 6. Then for 7, `$is_odd`

would be `1`

. Those are the only two value you’ll ever get for something that is `mod 2`

in PHP. And in PHP they can be used relatively interchangeably with `false`

and `true`

.

### Using PHP Modulus: Every 3 Items Gets Highlighted

If I know that I’ll only get two values when something is modulo 2, I also know that I’ll only get three values for `3`

. To concertize that, here’s a quick run of a few digits through modulus of 3 of integers in PHP:

```
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
```

We discussed that anything `mod 2`

in PHP will be either 0 or 1. And we can see above that anything `% 3`

is either 0, 1, or 2. I think you may be seeing the pattern. Any number as the “divisor” in a modulo operation will yield as results `0, 1, ..., n-2, n-1`

. So the last number you’ll ever get is one less than the number you’re using.

What all this means is that it’s pretty easy for us to highlight every third thing in PHP. Here’s a quick example:

```
$classes = array( 'block' );
for ( $i=0; $i < 100; $i++ ) {
if ( $i % 3 === 1 ) {
$css_classes[] = 'selected';
}
}
$classes_as_string = implode( ' ', $css_classes );
echo '<div class="'.$classes_as_string''">Number was '.$i.'<div>';
```

If you’re brand new to PHP, the above code sample may feel like you’ve been dunked under water. If you’ve been around, you’re likely needing no explanation here. So to help those who feel like they’re swimming right now:

- First we’ve got an array (or list) of CSS classes. In the first line, we’re simply seeing the default CSS class as the only item in that list. Which would be addressed in CSS (for example), with
`.block`

. The final output to our code means we could highlight the correct divs by either targeting the class`.selected`

or the compound of the two`.block.selected`

. - The
`for`

loop is just an easy way for me to write code that goes through a sequence of numbers. I still always have to look it up, but the first argument to`for`

is the starting value. The second is the “keep going condition”, and the last is what to do after an iteration through the loop. In our case, each time we’ll “increment the integer value of`$i`

.” - Our
`if`

is just making use of the modulo`%`

operator the rest of the article will be. We know that every third item will be`1`

but we also know that every third could either be`0`

or`2`

. I randomly used 1. - Then, if the condition was met, we add to the
`$css_classes`

array the value selected. (Somewhat explained in the first point). - Finally we making the CSS classes into a valid HTML statement by making the final
`echo`

ed output of our block`<div class="block selected">Number was 1<div>`

. The`implode`

will have made`array( 'block', 'selected' )`

into`block selected`

. It’ll “join” the array in its second argument with the character(s) of the first. So in our case, first element of the array`block`

, then the`selected`

element of the array.

### Using PHP Modulo: Every 4th Item Highlighted

If you’ve read carefully thus far, you may be able to guess a similar code snippet to the one above would work for every fourth item to be highlighted. You’re simply going to change the `3`

to a `4`

so you’d have:

```
$classes = array( 'block' );
for ( $i=0; $i < 100; $i++ ) {
if ( $i % 4 === 1 ) {
$css_classes[] = 'selected';
}
}
$classes_as_string = implode( ' ', $css_classes );
echo '<div class="'.$classes_as_string''">Number was '.$i.'<div>';
```

You could also write it slightly differently:

```
$classes = array( 'block' );
foreach ( range( 0, 99 ) as $i ) {
if ( $i % 4 === 1 ) {
$css_classes[] = 'selected';
}
}
$classes_as_string = implode( ' ', $css_classes );
echo '<div class="'.$classes_as_string''">Number was '.$i.'<div>';
```

Why rewrite it this way? Because I find `foreach`

easier to read. And I know that the range function will give me the array: `[0, 1, 2, ..., 98, 99]`

. So the effect is identical to the code above.

## What Getting Remainders does for Us in PHP

No need to belabor the point: modulus is a cool math thing. It’s also called “modulo.” And using modulos in a PHP is a great way to, among a few other things, quickly label every other, every third, every fourth, etc item in a list. Whether that list is rows of an HTML table, divs in a page, or anything else. If you absolutely need an highlighted row in PHP in some systematic may, modulo in PHP will do you well.

If you’re interested in learning more, we’ve got some great articles about math in PHP, building the best possible PHP conditionals, and doing logic in PHP. If not, good luck out there. We hope this has been helpful 🙂