The null coalescing operator ?? gives you a default value when something is missing or null.
<?php
$username = null;
echo $username ?? "Guest";
Guest
It reads as: “use $username, but if it does not exist or is null, use Guest.”
No warning for missing keys
The big advantage is that ?? never complains about a missing variable or array key.
<?php
$user = ["name" => "Lina"];
echo $user["name"] ?? "Unknown";
echo "\n";
echo $user["email"] ?? "No email";
Lina
No email
Without ??, reading $user["email"] would raise a warning about an undefined key.
With form data
This is where ?? is used most. A form field may not be sent at all.
<?php
$page = $_GET["page"] ?? 1;
$search = $_POST["q"] ?? "";
Chaining
You can chain several ??. PHP uses the first value that exists and is not null.
<?php
$nickname = null;
$name = "Lina";
echo $nickname ?? $name ?? "Guest";
Lina
?? vs ?:
?? checks whether a value is missing or null. The short ternary ?: checks whether it is falsy (0, “”, “0”, false, empty array).
<?php
$count = 0;
echo ($count ?? 10) . "\n"; // 0, because 0 is not null
echo ($count ?: 10); // 10, because 0 is falsy
0
10
Use ?? when 0 or an empty string are valid values.
??= assigns a default
<?php
$config = [];
$config["debug"] ??= false;
var_dump($config["debug"]);
bool(false)
Introduced in PHP 7
?? operator has existed since PHP 7.0, and ??= since PHP 7.4. Both are safe on any current version.