What is the null coalescing operator and how does it work?

Beginner

Answer

The null coalescing operator ?? (introduced in PHP 7.0) returns the first operand if it exists and is not null, otherwise returns the second operand. It's useful for providing default values.

$username = $_GET['user'] ?? 'guest';
// Equivalent to:
$username = isset($_GET['user']) ? $_GET['user'] : 'guest';

PHP 7.4 introduced the null coalescing assignment operator ??= for even more concise code.