Modulo math is very important to many fields of study. For example, we perform modulo 12 arithmatic any time we read an analog clock.
According to Wikipedia:
In mathematics, modular arithmetic (sometimes called clock arithmetic) is a system of arithmetic for integers, where numbers “wrap around” after they reach a certain value—the modulus.
PHP modulo arithmatic isn’t hard but it’s something you need in your set of tools as a PHP programmer. You might use it to check if a number is odd or even, to create a series of numbers that repeats (0, 1, 2, 0, 1, 2…), to find the remainder from a division problem, etc.
PHP uses the percent sign (%) to perform modulo arithmatic. For example:
<?php echo 4 % 12 . "\n"; echo 12 % 12 . "\n"; echo 13 % 12 . "\n"; echo 13.21 % 12.1 . "\n"; echo -13 % 12 . "\n"; ?>
will result in:
- Decimal values are stripped down to integers (13.6 becomes 13 for example)
- Negative values are taken into account (be careful not to forget…)
Back to Learn PHP in 24 Hours for more fun