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 ** 2 is 512, not 64.
  • 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;       // 1024

Watch out for floats: 0.1 + 0.2 is not exactly 0.3. Never compare floats with ===.

Example

Try it yourself
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.

Example · php
<?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.

Example · php
<?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;  // 0

Integer overflow to float

Adding 1 to PHP_INT_MAX silently promotes the result to float; use gmp or bcmath for true big-integer arithmetic.

Example · php
<?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

  • Be the first to comment on this lesson.