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
PHP Operators
PHP Ternary Operator
Exercises & Assignments
Write a PHP program to add two numbers
Interview Questions & Answers
What is the difference between == and === Operators in PHP?
What are the arithmetic operators in PHP?
What is the use of the ternary operator in PHP?
What is the null coalescing operator (??) in PHP?
What is the difference between division (/) and modulus (%) in PHP?
What is the difference between != and !== in PHP?
What is the difference between $var++ and $var + 1 in PHP?