You have used = to put a value in a variable. PHP also has shorthand operators that combine a calculation with an assignment.
| Shorthand | Same 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 |
<?php
$score = 10;
$score += 5; // 15
$score -= 3; // 12
$score *= 2; // 24
$score /= 4; // 6
echo $score;
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.
<?php
$html = "<ul>";
$html .= "<li>One</li>";
$html .= "<li>Two</li>";
$html .= "</ul>";
echo $html;
<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.
<?php
$settings = ["theme" => "dark"];
$settings["theme"] ??= "light"; // already set, stays "dark"
$settings["lang"] ??= "en"; // missing, so it is added
print_r($settings);
Array
(
[theme] => dark
[lang] => en
)
Assignment gives back a value
An assignment is an expression, so you can use its result.
<?php
$a = $b = 5;
echo $a + $b;
10
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.