Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Operators

PHP arithmetic operators

Reference for PHP arithmetic operators: addition, subtraction, multiplication, division, modulo, exponent, intdiv(), negation and their error cases.

Arithmetic operators work on numbers: + adds, - subtracts, * multiplies, / divides, % gives the remainder, and ** raises to a power. A unary - negates and a unary + converts to a number. Numeric strings are converted automatically; non-numeric strings throw a TypeError in PHP 8.

The result type follows the operands. Integer operations stay integers until they overflow, then become floats. / returns an integer only when both operands are integers and the division is exact.

PHP
echo 7 + 3, " ", 7 / 2, " ", 7 % 3, " ", 2 ** 10;

Try it

PHP The six operators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Errors and conversions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
$a + $b    $a - $b    $a * $b    $a / $b
$a % $b    $a ** $b   -$a        +$a
intdiv(int $num1, int $num2): int
Operator Result
+, -, * Sum, difference, product. Integer overflow produces a float.
/ Quotient. Integer if both are integers and divisible, otherwise float.
% Remainder after converting both operands to integers. The sign follows the left operand.
** Power. Right associative: 2 ** 3 ** 2 is 2 ** 9.
-$a, +$a Negation and conversion to a number.

Errors: / or % by zero throws DivisionByZeroError. intdiv(PHP_INT_MIN, -1) throws ArithmeticError. A non-numeric string operand throws TypeError; a string with leading digits like "5 apples" is used as 5 with a warning ("A non-numeric value encountered").

Usage notes

  • % is integer-only. Floats are truncated first. Use fmod() for float remainders.
  • Sign of %. -7 % 3 is -1. For a result that is never negative use (($a % $n) + $n) % $n.
  • intdiv() truncates toward zero, unlike floor($a / $b), which rounds down.
  • Float precision. 0.1 + 0.2 == 0.3 is false. Compare with a tolerance or use integers (cents) for money.
  • ** precedence. It binds tighter than unary minus: -2 ** 2 is -4.
  • Arrays. + on arrays is a union, not addition. See array operators.
  • Increment and decrement have their own page: ++ and --.