How to Use the Null Coalescing Operator in PHP

This article explains how the null coalescing operator (??) works in PHP to simplify your code. You will learn its basic syntax, how it handles undefined variables without throwing notices, how to chain multiple operators, and how it compares to the traditional ternary operator and the isset() function.

What is the Null Coalescing Operator?

Introduced in PHP 7.0, the null coalescing operator (??) is a shorthand syntax designed to handle common scenarios where you need to check if a variable is set and not null, and provide a fallback value if it is.

The basic syntax is:

$result = $value1 ?? $value2;

This expression evaluates to $value1 if $value1 exists and is not null. Otherwise, it evaluates to $value2.

Simplifying isset() and the Ternary Operator

Before PHP 7, developers had to combine the ternary operator (? :) with the isset() function to safely assign default values to variables that might not be defined.

// Old way (before PHP 7)
$username = isset($_GET['user']) ? $_GET['user'] : 'anonymous';

With the null coalescing operator, you can write the exact same logic in a much cleaner, shorter format:

// Modern way (PHP 7+)
$username = $_GET['user'] ?? 'anonymous';

If the $_GET['user'] parameter is not present in the request URL, or if its value is explicitly set to null, the $username variable will safely default to 'anonymous'. This syntax automatically prevents PHP from throwing an “Undefined index” or “Undefined variable” warning.

Chaining Multiple Operators

You can chain multiple null coalescing operators together. PHP will evaluate them from left to right and return the first value that is defined and not null.

$username = $_GET['user'] ?? $_POST['user'] ?? 'guest';

In this example, PHP first checks if $_GET['user'] is set. If not, it checks $_POST['user']. If both are undefined or null, it falls back to the string 'guest'.

Difference Between Null Coalescing and Ternary Operators

The null coalescing operator is not a complete replacement for the shorthand ternary operator (?:). They behave differently when dealing with falsy values (like 0, false, "", or []).

$status = 0;

$result1 = $status ?? 1; // Returns 0 (0 is not null)
$result2 = $status ?: 1;  // Returns 1 (0 evaluates to false)

The Null Coalescing Assignment Operator (PHP 7.4+)

In PHP 7.4, the null coalescing assignment operator (??=) was introduced to allow you to easily assign a default value to a variable if it is not already set.

// This code:
$config['theme'] ??= 'dark';

// Is equivalent to this:
$config['theme'] = $config['theme'] ?? 'dark';