What is the null coalescing operator in PHP?
Why Interviewers Ask This
This question tests conceptual clarity. Interviewers want to hear a precise, confident definition before moving to more complex PHP topics. It also reveals how well you can explain technical ideas to non-experts.
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.
Pro Tip
Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a PHP codebase.