🐘 PHP Beginner

What is the null coalescing operator in PHP?

Answer

The null coalescing operator (??), introduced in PHP 7, returns the left operand if it exists and is not null, otherwise returns the right operand. It is equivalent to isset($var) ? $var : $default but much more concise. Example: $username = $_GET["user"] ?? "Guest";. It can be chained: $val = $a ?? $b ?? $c ?? "default"; — returns the first non-null value. PHP 7.4 added the null coalescing assignment operator (??=): $data["key"] ??= "default"; assigns the right side only if the left side is null or does not exist. This operator is very common in PHP for handling missing GET/POST parameters and optional array keys.