Menu
CoddyTech

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. When dividing by 2, the remainder is 0 for an even number and 1 for an odd number (-1 if the odd number is negative), so if a number divided by 2 has no remainder, it's even; otherwise, it's odd:

<?php
$number = 8;
echo $number % 2; // Outputs: 0 (even)

$number = 7;
echo $number % 2; // Outputs: 1 (odd)
?>

This only works for even/odd checks because dividing by 2 always gives a remainder of 0 or 1 (or -1 for a negative odd number). With other divisors, when both numbers are positive, the remainder can be any value from 0 up to one less than the divisor. The result takes the sign of the number being divided, so -17 % 5 is -2.

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)

$dividend = 17;
$divisor = 5;
echo $dividend % $divisor; // Outputs: 2 (17 = 5*3 + 2)
?>
challenge icon

Challenge

Easy

Read 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).

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;
?>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Online PHP compiler