Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 147 ยท Operators

Arithmetic and Assignment Operators

Learn PHP arithmetic operators (+ - * / % **), precedence, compound assignment like += and .=, increment and decrement, and the new string increment rules.

An operator is a symbol that does something with one or more values, called its operands. In $price * 3, the * is the operator and $price and 3 are the operands. This chapter goes through PHP's operators family by family, starting with the two you'll type most: arithmetic operators, which calculate, and assignment operators, which store results in variables.

Most arithmetic operators work just as they did in math class, so this lesson concentrates on what's specific to PHP: which operator binds tighter than which, what / and % return, the shortcuts like += and .=, the difference between $i++ and ++$i, and a corner of PHP that is being cleaned up right now: incrementing strings.

You'll need the number basics from Integers and Floats. If you're unsure how a string or null becomes a number in arithmetic, Type Juggling and Casting has the rules.

The arithmetic operators

Operator Name Example Result
+ Addition 7 + 2 9
- Subtraction 7 - 2 5
* Multiplication 7 * 2 14
/ Division 7 / 2 3.5
% Modulo (remainder) 7 % 2 1
** Exponentiation (power) 7 ** 2 49
-$x Negation -(7) -7
+$x Identity (converts to a number) +'7' 7

The result type follows simple rules. If both operands are integers and the result fits in an int, you get an int; if either operand is a float, you get a float. Division is the exception: / returns a float unless both operands are integers and the division is exact (8 / 2 is int(4), 7 / 2 is float(3.5)). And % always works on integers and returns an integer.

PHP A shopping receipt

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.

$subtotal is int(28), but $discount is float(4.2) because 28 ร— 15 / 100 isn't a whole number, and so $total becomes float(23.8). Once a float enters a calculation, everything downstream is a float. (For real prices, use integer cents or bcmath, as explained in Math Functions.)

Division and modulo by zero

Both / and % throw a DivisionByZeroError when the right side is zero; there's no warning and no INF result. Guard the divisor whenever it can be zero, for example an average of an empty list:

PHP
$count = count($scores);
$average = $count > 0 ? array_sum($scores) / $count : 0;

% truncates both operands to integers first (7.9 % 3 is 1, with a deprecation notice about the lost precision), and its result has the sign of the left operand: -7 % 3 is -1. Use fmod() for float remainders.

Common uses of %

The remainder operator solves many everyday problems: alternating row colors, doing something every Nth time, and wrapping an index around:

PHP Practical modulo

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.

$i % $tables cycles through 0, 1, 2, 0, 1, which deals guests round-robin to the three tables. The time example splits seconds into hours, minutes and seconds and prints 01:02:05 (printf is covered in Formatting Strings).

Precedence and associativity

When an expression contains several operators, precedence decides which runs first, exactly like in math: 2 + 3 * 4 is 14, not 20. When operators have the same precedence, associativity decides the direction:

Precedence (high to low) Operators Associativity
1 ** right
2 ++, --, unary - and +, casts (unary)
3 *, /, % left
4 +, - left
5 . (PHP 8+) left
... comparisons, logical operators
lowest =, +=, -= and the other assignments right
PHP Precedence surprises

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.

The output is 14, 20, 3, 10, then three that catch people out:

  • 2 ** 3 ** 2 is 512, because ** is right-associative: it means 2 ** (3 ** 2), which is 29.
  • -2 ** 2 is -4, because ** binds tighter than the minus sign: it means -(2 ** 2). Write (-2) ** 2 to square a negative number.
  • 'Sum: ' . 1 + 2 prints Sum: 3, because since PHP 8, + and - bind tighter than ..

When in doubt, add parentheses. They cost nothing and make your intent obvious to the next reader. The complete precedence table, including every operator family, is in Bitwise, String, Array and Pipe Operators.

Assignment

The basic assignment operator = stores the value on the right in the variable on the left. It's an expression itself: its value is the value that was assigned. That's why chained assignment works, and why you can assign inside a condition:

PHP
$width = $height = 100;          // both are 100 (right-associative)

if (($line = fgets(STDIN)) !== false) {
    echo "Read: $line";
}

The parentheses around $line = fgets(STDIN) matter: assignment has very low precedence, so without them $line would receive the result of the comparison (true or false) instead of the line.

Compound assignment

Writing $total = $total + $price; is so common that PHP has a shorthand for every arithmetic operator, plus concatenation and null coalescing:

Shorthand Same as
$a += $b $a = $a + $b
$a -= $b $a = $a - $b
$a *= $b $a = $a * $b
$a /= $b $a = $a / $b
$a %= $b $a = $a % $b
$a **= $b $a = $a ** $b
$a .= $b $a = $a . $b
$a ??= $b $a = $a ?? $b (assign only if null or missing)

There are bitwise versions too (&=, |=, ^=, <<=, >>=), covered in Bitwise, String, Array and Pipe Operators.

PHP Compound assignment in a loop

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.

.= is the idiomatic way to build up a string piece by piece, and += is how you accumulate a total. Note that $balance /= 2 makes $balance an int (35) here because 70 / 2 divides exactly; $balance /= 3 would have made it a float.

Increment and decrement

++ adds 1 to a variable and -- subtracts 1. Each comes in two forms, and the difference matters when you use the result in a larger expression:

  • Pre-increment ++$i: increments first, then gives you the new value.
  • Post-increment $i++: gives you the old value, then increments.
PHP Prefix versus postfix

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.

The output:

TEXT
a = 6, b = 5
c = 6, d = 6
first
second
i is now 2
3... 2... 1... liftoff!

Used as a statement on its own line ($i++;), the two forms do exactly the same thing. Use them inside expressions sparingly: $queue[$i++] is a well-known idiom, but something like $i++ + ++$i is legal and unreadable. Write two lines instead.

Incrementing PHP_INT_MAX turns the variable into a float, just like + 1 does. Incrementing null gives 1, but decrementing null leaves it null and, since PHP 8.3, produces a warning. Incrementing or decrementing a bool has no effect and also warns. These are almost always bugs: initialize your counters to 0.

Incrementing strings (and why to stop)

PHP has a curious old feature: ++ on a non-numeric string increments it like a car odometer of letters. 'a' becomes 'b', 'Az' becomes 'Ba', and 'zz' becomes 'aaa'. Numeric strings are simply treated as numbers: '5' becomes 6.

The letter behavior has odd edge cases (-- never worked on letters at all, and 'a9' becomes 'b0'), so it's being phased out. PHP 8.3 added two explicit functions, str_increment() and str_decrement(), and began deprecating the operator form for odd strings; PHP 8.5 completed it. On PHP 8.5, which our editor runs, every ++ on a non-numeric string triggers a deprecation notice:

PHP String increment, old and new

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.

The numeric string becomes int(8) without complaint, and the str_increment()/str_decrement() calls print b, Ba, aaa and Az. The last part shows the deprecated form on purpose: you get Deprecated: Increment on non-numeric string is deprecated, use str_increment() instead in main.php on line 12, then string(1) "Z". If you need letter sequences (spreadsheet columns, for example), call str_increment(). It's clear about its intent and works the same in every future version.

String concatenation is an operator too

PHP keeps arithmetic and text separate: + always adds numbers, and the dot . always joins strings. Its assignment form .= appends:

PHP
$name = 'Ada';
$greeting = 'Hello, ' . $name . '!';   // 'Hello, Ada!'
$greeting .= ' Welcome back.';          // 'Hello, Ada! Welcome back.'
echo '3' + '4';                         // 7
echo '3' . '4';                         // 34

Using + on strings that aren't numeric throws a TypeError (Unsupported operand types: string + string), which is PHP's way of telling you that you meant .. Strings and concatenation are covered in detail in Strings.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does var_dump(10 / 4); print?

    Division returns a float unless both operands are integers and the result is exact. Use intdiv(10, 4) for the integer quotient 2.
  2. 2. What is the value of -3 ** 2?

    ** binds tighter than the unary minus, so this is -(3 ** 2) = -9. Write (-3) ** 2 to get 9.
  3. 3. $i = 3; $j = $i++ * 2; What are $i and $j?

    Post-increment returns the old value (3) for the multiplication, then increments $i to 4. With ++$i, $j would be 8.
  4. 4. $text = 'Hi'; $text .= ' there'; $text .= '!'; What is $text?

    .= appends to the existing string each time, so the pieces are joined in order.
  5. 5. What does echo 17 % 5; print?

    17 divided by 5 is 3 with a remainder of 2. The modulo operator returns the remainder.

Summary

  • Arithmetic operators are +, -, *, /, % and **. Ints stay ints unless a float is involved; / returns an int only for exact integer division; / 0 and % 0 throw DivisionByZeroError.
  • % returns an integer remainder with the sign of the left operand. It's great for alternating, every-Nth and wrap-around logic.
  • Precedence follows math rules. ** is right-associative and binds tighter than unary minus (-2 ** 2 is -4); +/- bind tighter than . since PHP 8. Use parentheses when unsure.
  • = is an expression that returns the assigned value. Compound forms like +=, *=, .= and ??= update a variable in place.
  • ++$i returns the new value; $i++ returns the old one. Don't increment null or booleans.
  • Incrementing non-numeric strings is deprecated in PHP 8.5; use str_increment() and str_decrement() (PHP 8.3+).

Next: Comparison Operators