What does double question mark (??) operator mean in PHP ?

PHP 7 introduced the double question mark (??) operator, known as the Null Coalescing Operator. This operator returns its first operand if it exists and is not NULL; otherwise, it returns its second operand.

The null coalescing operator evaluates from left to right and can be chained together for multiple fallback values. It's particularly useful for providing default values when working with potentially undefined variables.

Syntax

$result = $variable ?? $default_value;

Basic Example

Here's how the null coalescing operator works with an undefined variable −

<?php
    // $a is not defined
    echo $a ?? 9 ?? 45;
?>
9

Example with Defined Variable

When the first variable is defined and not null, it returns that value −

<?php
    // $a is not defined, but $b is defined
    $b = 34;
    echo $a ?? $b ?? 7;
?>
34

Comparison with isset()

The null coalescing operator provides a shorter alternative to using isset()

<?php
    $username = null;
    
    // Traditional approach
    $name1 = isset($username) ? $username : 'Guest';
    
    // Using null coalescing operator
    $name2 = $username ?? 'Guest';
    
    echo "Traditional: " . $name1 . "<br>";
    echo "Null coalescing: " . $name2;
?>
Traditional: Guest
Null coalescing: Guest

Conclusion

The null coalescing operator (??) provides a clean and concise way to handle undefined or null variables by offering default values. It's more readable than traditional isset() checks and supports chaining for multiple fallback options.

Updated on: 2026-03-15T08:14:01+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements