PHP Assignment Operators
In this page:
Basic Assignment (=)
= stores the value on the right into the variable on the left — the most basic operation in PHP, and the one every other assignment operator below is a shorthand for.
Example: Basic Assignment (=)
<?php
$total = 5;
echo $total;
?>
Login to try C/C++/Java/PHP code in the editor
Add and Subtract Assignment
+= and -= combine an operation with an assignment in one step: $total += 5 is exactly equivalent to $total = $total + 5, just shorter to write and, for many people, easier to read once the pattern becomes familiar.
Example: Add and Subtract Assignment
<?php
$total = 10;
$total += 5;
echo $total . "\n";
$total -= 3;
echo $total;
?>
Login to try C/C++/Java/PHP code in the editor
Multiply and Divide Assignment
*= and /= follow the identical pattern for multiplication and division — $price *= 1.1 applies a 10% increase to $price and stores the result back into the same variable in a single statement.
Example: Multiply and Divide Assignment
<?php
$price = 100;
$price *= 1.1;
echo $price;
?>
Login to try C/C++/Java/PHP code in the editor
Modulo and Concat Assignment
%= reassigns a variable to the remainder of dividing it by another value, and .= appends a string onto the end of an existing string variable — the string-concatenation equivalent of += for numbers, and one of the most common operators in code that builds up HTML output piece by piece.
Example: Modulo and Concat Assignment
<?php
$n = 10;
$n %= 3;
echo $n . "\n";
$html = "<p>";
$html .= "Hello";
$html .= "</p>";
echo $html;
?>
Login to try C/C++/Java/PHP code in the editor
Null Coalescing Assignment (??=)
??= only assigns the right-hand value if the left-hand variable is currently null or doesn't exist yet — it leaves an already-set variable untouched. That makes it the concise way to fill in a default value without first writing an explicit isset() check.
Example: Null Coalescing Assignment (??=)
<?php
$username = null;
$username ??= "Guest";
echo $username;
?>
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: