1 min read

PHP Null Coalescing Operator (??)

The null coalescing operator ?? was introduced in PHP 7. It is used to return the first operand if it exists and is not null; otherwise, it returns the second operand.


1. Basic Usage

It is essentially syntactic sugar for the common case of needing to use a ternary in conjunction with isset().

// Old way
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';

// New way with ??
$username = $_GET['user'] ?? 'nobody';

2. Chaining

You can chain the operators. The first defined value (reading from left to right) will be returned.

$val = $input ?? $default ?? "fallback";

3. Null Coalescing Assignment (??=)

Introduced in PHP 7.4, this operator assigns a value to a variable only if that variable is currently null.

// Old way
if (!isset($username)) {
    $username = 'Guest';
}

// New way
$username ??= 'Guest';

4. Comparison with Ternary (?:)

The shorthand ternary operator ?: checks for truthiness, whereas ?? checks if the value is set and not null.

$a = false;

echo $a ?? "a is not set"; // Outputs: false (because $a is set, even if false)
echo $a ?: "a is false";   // Outputs: "a is false"

programming/php/php programming/php/php-operators