What is the ?? operator in PHP?
Short answer
?? returns the left side unless it is null or undefined, in which case it returns the right side. Unlike ?:, it suppresses the undefined-key warning and does not treat 0 or "" as absent.
$name = $_POST['name'] ?? 'guest';#The three lookalikes
$a = $value ?? 'default'; // null coalescing
$b = $value ?: 'default'; // short ternary — checks falsiness
$c = isset($value) ? $value : 'default'; // the long form ?? replacesThe difference shows up on falsy-but-present values:
$count = 0;
$count ?? 5; // 0 — it is set, so it wins
$count ?: 5; // 5 — 0 is falsy, so the default winsFor a quantity, a page number or a score, ?: silently replaces a legitimate zero. ?? does not.
?: also emits a warning if the variable does not exist. ?? never does — that is its main job.
#Chaining
$value = $a ?? $b ?? $c ?? 'fallback';Evaluation is left to right and stops at the first non-null.
#Assignment form
$config['timeout'] ??= 30; // set only if missing or null#Nullsafe method calls
Related, and often confused with it:
$country = $user?->address?->country;?-> returns null instead of throwing when the left side is null. Useful for optional relations — but be careful not to use it to paper over a null that should never have happened.