Arithmetic and Strings

Arithmetic, String and Assignment Operators

The arithmetic operators are +, -, *, /, % and the right-associative **. / returns an int only for exact division, so use intdiv() for whole numbers; % takes its left operand's sign, and fmod() is the float version. Strings join with .. Every binary operator has a compound form such as .= or **=, and an assignment yields its value, so $a = $b = 5 sets both. $n++ yields the old value and ++$n the new one.

Arithmetic, concatenation and compound assignmentPHP
<?php
echo 7 / 3, " | ", intdiv(7, 3), " | ", 6 / 2, "\n";      // float unless exact
echo -7 % 3, " | ", fmod(7.5, 2), " | ", 2 ** 3 ** 2, "\n"; // 2 ** 3 ** 2 is 2 ** 9
$price = 20;
$label = "Order";
$label .= " #" . $price * 3;                 // compound assignment; * binds before .
echo "Sum: " . $price + 3, " | $label\n";    // since 8.0: "Sum: " . ($price + 3)
$n = 5;
echo $n++, " ", $n, " ", ++$n, "\n";         // post-, then pre-increment
try { echo 1 % 0; } catch (DivisionByZeroError $e) { echo $e->getMessage(), "\n"; }
echo fdiv(1, 0), "\n";
Output
2.3333333333333 | 2 | 3
-1 | 1.5 | 512
Sum: 23 | Order #60
5 6 7
Modulo by zero
INF

Before PHP 8.0 the Sum: line meant ("Sum: " . 20) + 3; concatenation now binds more loosely than arithmetic. Division or modulo by zero throws DivisionByZeroError (8.0), while fdiv() returns INF or NAN. Arithmetic on an array throws TypeError, except +, which is array union (Arrays and the Array Library), and ++ on a non-numeric string is deprecated in 8.5 in favor of str_increment().