Skip to content

PHP Tutorial Operators

Assignment Operators

Lesson 48 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

You have used = to put a value in a variable. PHP also has shorthand operators that combine a calculation with an assignment.

ShorthandSame as
$x += 5$x = $x + 5
$x -= 5$x = $x - 5
$x *= 5$x = $x * 5
$x /= 5$x = $x / 5
$x %= 5$x = $x % 5
$x **= 2$x = $x ** 2
$s .= "text"$s = $s . "text"
$x ??= 5$x = $x ?? 5
index.php
PHP
<?php
$score = 10;

$score += 5;   // 15
$score -= 3;   // 12
$score *= 2;   // 24
$score /= 4;   // 6

echo $score;
Output
OUTPUT
6

Building a string

.= adds text to the end of a string. It is the usual way to build up a larger text piece by piece.

index.php
PHP
<?php
$html = "<ul>";
$html .= "<li>One</li>";
$html .= "<li>Two</li>";
$html .= "</ul>";

echo $html;
Output
OUTPUT
<ul><li>One</li><li>Two</li></ul>

Default values with ??=

??= sets a variable only if it is missing or null. It is great for defaults.

index.php
PHP
<?php
$settings = ["theme" => "dark"];

$settings["theme"] ??= "light";   // already set, stays "dark"
$settings["lang"] ??= "en";       // missing, so it is added

print_r($settings);
Output
OUTPUT
Array
(
    [theme] => dark
    [lang] => en
)

Assignment gives back a value

An assignment is an expression, so you can use its result.

index.php
PHP
<?php
$a = $b = 5;
echo $a + $b;
Output
OUTPUT
10
warning
Confusing = and ==
= stores a value. == compares two values. Writing if ($x = 3) assigns 3 to $x and is always true. See the next lessons on comparison.