What is the null coalescing operator (??) in PHP?
The null coalescing operator (??) returns the left value if it exists and is not NULL, otherwise it returns the right value. It is a short form of isset() with a ternary operator, and it never gives an “undefined” warning.
<?php
$user = ["name" => "Robin"];
echo $user["city"] ?? "Not given";
echo "<br>";
echo $user["name"] ?? "Not given";
?>
Output:
Tutorials Class - Output Window
Not given
Robin
From PHP 7.4 you can also use ??=. It sets the value only when the variable is not set or is NULL.
<?php
$settings = [];
$settings["theme"] ??= "light";
echo $settings["theme"];
?>
Output:
Tutorials Class - Output Window
light
It is very useful with $_GET and $_POST, for example $page = $_GET["page"] ?? 1;. See also PHP isset().
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |