» » » Php Mod Modulus Modulo

# Modulus (Mod), Modulo and PHP – Explanation and Code Examples

This article will explain (in the simplest terms possible) what modulus and modulo mean and how they are calculated in the PHP programming language.

## Modulus and Modulo are NOT the Same Things!

There’s a bit of confusion about this, and it seems that in some places, the terms are used interchangeably – this is wrong (and confused me too – hence this article)!

## What is Modulus?

In mathematics, the modulus is the absolute value of a number. It’s the non-negative value of a number – or its distance from 0 (zero).

So, the modulus of 3 is 3, and the modulus of -3 is also 3.

### Calculating the Modulus in PHP

The abs() function in PHP calculate the absolute value of a number. Here it is in use:

`abs(3);`

Simply pass a number to the abs() function, and the absolute value (modulus) of the number will be returned.

### What Is It Used For?

The modulus of a number is frequently used in physics calculations – particularly when calculating momentum and collisions. The sign (positive or negative) of a number representing movement may indicate its direction, while the modulus represents the speed of movement.

If you’re coding video games, you’ll certainly put it to good use.

## What is Modulo?

In programming, the modulo is an arithmetic operator – it calculates the remainder left when one number is divided by another.

### What is a Remainder?

The remainder is a mathematical term – it’s the amount left-over when one number has been divided by another if the first number cannot be divided by the second exactly.

So, 6 ÷ 3 has a remainder of 0, as 6 can be cleanly divided by 3 with nothing left over.

However, 7 ÷ 3 has a remainder of 17 cannot be divided into 3 equal values, the nearest number less than 7 which can be cleanly divided by 3 is 6 – leaving 1 remainder.

### Calculating the Modulo in PHP

In PHP, it is represented by the % (percent) symbol.

Here it is in action:

`\$remainder = 7 % 3; // 7 can be divided by 3 twice, leaving a remainder of 1`

Above, the variable \$remainder will be given a value of 1 – the remainder when 7 has been divided by 3.

## Don’t Mix Them Up!

Mixing the terms modulus and modulo up probably won’t have any long-term side effects on your health, but it’ll make searching for solutions online really frustrating.

SHARE:
Categories PHP Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.