What is the difference between division (/) and modulus (%) in PHP?
The division operator (/) gives the result of dividing one number by another. The modulus operator (%) gives only the remainder of that division.
<?php
$a = 10;
$b = 3;
echo $a / $b . "<br>"; // division
echo $a % $b . "<br>"; // modulus (remainder)
echo intdiv($a, $b); // whole number part only
?>
Output:
Tutorials Class - Output Window
3.3333333333333
1
3
Modulus is often used to check even or odd numbers. If $number % 2 is 0, the number is even.
Note:
In PHP 8, dividing or using modulus with zero throws a DivisionByZeroError. Check the divisor before the calculation.
Learn more about the similar topics:
| Tutorials |
|---|
| PHP Operators |
| Exercises & Assignments |
|---|
| Write a PHP program to add two numbers |
| Write a PHP program to check whether a number is positive, negative or zero |