Assignment operators are used with numeric values to write a value to a variable. The most basic assignment operator is the equal sign (=), which sets the value of the left operand to the value of the expression on the right.
In PHP, the = does not mean "equals" (that is handled by comparison operators). Instead, it means **"set the value of."**
<?php
$x = 10; // $x now holds the value 10
?>
PHP also provides "shorthand" operators that combine a mathematical operation with assignment.
| Operator | Same as... | Description |
|---|---|---|
x = y |
x = y |
Assigns value of y to x |
x += y |
x = x + y |
Addition and assignment |
x -= y |
x = x - y |
Subtraction and assignment |
x *= y |
x = x * y |
Multiplication and assignment |
x /= y |
x = x / y |
Division and assignment |
x %= y |
x = x % y |
Modulus and assignment |
Using shorthand operators makes your code cleaner and easier to read, especially when updating totals in a loop.
<?php
$total = 100;
$tax = 15;
$total += $tax; // Instead of $total = $total + $tax;
echo $total; // Outputs: 115
?>
$x = $y is an **assignment**, while $x == $y is a **comparison**. Distinguishing these two is vital for logic!
.= to append a string to an existing variable. (e.g., $name .= " Doe";).
+=) combine math and assignment.