← Back to PHP Course | Chapter 3: Operators | Lesson 5 of 8

PHP Assignment Operators

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
<?php
$total = 5;
echo $total;
?>

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
<?php
$total = 10;
$total += 5;
echo $total . "\n";
$total -= 3;
echo $total;
?>

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
<?php
$price = 100;
$price *= 1.1;
echo $price;
?>

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
<?php
$n = 10;
$n %= 3;
echo $n . "\n";

$html = "<p>";
$html .= "Hello";
$html .= "</p>";
echo $html;
?>

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
<?php
$username = null;
$username ??= "Guest";
echo $username;
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.