PHP Arithmetic Operators
In this page:
Addition and Subtraction
+ and - perform the addition and subtraction you'd expect on numbers, and PHP will automatically convert numeric-looking strings ("5" + 3) to numbers before operating — a convenience that's handy for form input but worth being aware of, since it can mask a typo that produced a non-numeric string.
Example: Addition and Subtraction
<?php
echo 10 + 5, "\n";
echo 10 - 5, "\n";
echo "5" + 3;
?>
Login to try C/C++/Java/PHP code in the editor
Multiplication and Division
* multiplies two values, and / divides them — but PHP's division always returns a float the moment the result isn't a whole number, even if both operands were integers. 10 / 3 gives 3.3333..., not an integer with a dropped remainder, which surprises people coming from languages that do integer division by default.
Example: Multiplication and Division
<?php
echo 4 * 3, "\n";
echo 10 / 3;
?>
Login to try C/C++/Java/PHP code in the editor
Modulo Operator
% returns the remainder left over after dividing two integers, which makes it the standard tool for checking parity ($n % 2 === 0 for even) or for cycling through a fixed range of values, like wrapping an index back to zero once it passes the end of an array.
Example: Modulo Operator
<?php
$n = 7;
echo $n % 2 === 0 ? "even" : "odd";
?>
Login to try C/C++/Java/PHP code in the editor
Exponentiation Operator
** raises the left-hand number to the power of the right-hand one — 2 ** 8 evaluates to 256. It's PHP's direct replacement for the older, clunkier pow() function call for this exact purpose, and reads more naturally in a formula.
Example: Exponentiation Operator
<?php
echo 2 ** 8;
?>
Login to try C/C++/Java/PHP code in the editor
Increment and Decrement Operators
++ and -- add or subtract exactly 1 from a variable in place. Written before the variable (++$x) they update the value and then return it; written after ($x++) they return the *original* value first and only then apply the update — a distinction that matters the moment you use the result of the expression itself.
Example: Increment and Decrement Operators
<?php
$x = 5;
echo ++$x . "\n"; // pre-increment: 6
$y = 5;
echo $y++ . "\n"; // post-increment: 5
echo $y; // now 6
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: