Modulo Operator
Part of the Fundamentals section of Coddy's PHP journey — lesson 16 of 71.
The modulo operator (%) returns the remainder after division. When you divide one number by another, modulo gives you what's left over.
<?php
echo 10 % 3; // Outputs: 1
?>Here, 10 divided by 3 equals 3 with a remainder of 1. The modulo operator returns that remainder.
A common use of modulo is checking if a number is even or odd. If a number divided by 2 has no remainder, it's even. Because we're dividing by 2, the only possible remainders are 0 (even) or 1 (odd) — unlike general modulo operations, where the remainder can be any value from 0 up to the divisor minus 1.
<?php
$number = 8;
echo $number % 2; // Outputs: 0 (even)
$number = 7;
echo $number % 2; // Outputs: 1 (odd)
?>More examples to help you understand the pattern:
<?php
echo 15 % 4; // Outputs: 3 (15 = 4*3 + 3)
echo 20 % 5; // Outputs: 0 (20 = 5*4 + 0)
?>Challenge
EasyRead two numbers from input: a dividend and a divisor.
Calculate and print the remainder when the first number is divided by the second number.
Example:
If the inputs are 17 and 5, the output should be 2 (because 17 ÷ 5 = 3 with a remainder of 2).
Cheat sheet
The modulo operator (%) returns the remainder after division:
<?php
echo 10 % 3; // Outputs: 1
?>Common use case - checking if a number is even or odd:
<?php
$number = 8;
echo $number % 2; // Outputs: 0 (even)
$number = 7;
echo $number % 2; // Outputs: 1 (odd)
?>Additional examples:
<?php
echo 15 % 4; // Outputs: 3 (15 = 4*3 + 3)
echo 20 % 5; // Outputs: 0 (20 = 5*4 + 0)
?>Try it yourself
<?php
// Read input
$dividend = intval(fgets(STDIN));
$divisor = intval(fgets(STDIN));
// TODO: Write your code below to calculate the remainder
// Output the result
echo $remainder;
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Comparison & Logical Operators
Comparison OperatorsEquality & IdentityLogical Operators Part 1Logical Operators Part 2Recap - Simple Logic2Variables and Data Types
NumbersStrings and QuotesBooleansNaming ConventionsRecap - Variable InitEmpty VariablesString ConcatenationGetting User InputCast to Different Types5Conditional Logic
If StatementIf - ElseThe Ternary OperatorNull Coalescing OperatorSwitch StatementRecap - Making Decisions3Basic Operators
Arithmetic OperatorsModulo OperatorExponentiation OperatorCombined AssignmentIncrement/DecrementOperator PrecedenceRecap - Simple CalculationsString Operators