Arithmetic Operators, In Depth
Beyond + - * /: exponentiation **, modulo %, integer division intdiv() and the traps of float precision.
You already know +, -, * and /. The details are where real bugs hide. Division / in PHP always gives a float when the numbers don't divide evenly, and dividing by zero throws a DivisionByZeroError rather than returning infinity.
The full arithmetic set
%modulo works on integers (operands are cast to int first).**is exponentiation and is right-associative:2 ** 3 ** 2is512, not64.intdiv($a, $b)gives a true integer division;fmod($a, $b)gives a float remainder.
Easy example
<?php
$a = 17;
$b = 5;
echo $a / $b; // 3.4 (float)
echo intdiv($a, $b); // 3 (int)
echo $a % $b; // 2
echo 2 ** 10; // 1024Watch out for floats: 0.1 + 0.2 is not exactly 0.3. Never compare floats with ===.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Use ** for exponentiation to compute compound interest without importing a math library.
- Apply intdiv() when splitting a batch of records into fixed-size pages to get a whole-number count.
- Use fmod() instead of % when computing remainders on floating-point currency amounts.
More examples
Exponentiation and intdiv
** raises to a power (right-associative); intdiv() returns integer division without the decimal remainder.
<?php
$compound = 1000 * (1.05 ** 10); // 1000 * 1.05^10
echo round($compound, 2); // 1628.89
$pages = intdiv(105, 10); // 10 full pages
echo $pages;Float precision trap with %
The % operator casts operands to int first; use fmod() for float modulo to preserve decimal precision.
<?php
$price = 10.50;
$change = fmod($price, 1.00); // correct: 0.5
$wrong = $price % 1; // int cast first -> 0
echo $change; // 0.5
echo $wrong; // 0Integer overflow to float
Adding 1 to PHP_INT_MAX silently promotes the result to float; use gmp or bcmath for true big-integer arithmetic.
<?php
$big = PHP_INT_MAX;
echo gettype($big); // integer
$overflow = $big + 1;
echo gettype($overflow); // double (PHP promotes silently)
echo $overflow; // 9.2233720368548E+18
Discussion