PHP Null Coalescing Operator: Handling Null Values

php null coalescing operator

The PHP null coalescing operator, written as ??, is a helpful feature added in PHP 7. It makes it easier to set default values for variables that might be null.

Many modern programming languages have similar operators to handle null or undefined values.

It gives you a short and clear way to handle values that can be null without using long ternary checks.

Let’s look at its syntax.

Null Coalescing Operator Syntax

The syntax of the null coalescing operator (??) is simple. You use it when a variable might be null or not set. If the variable is null, it gives you a default value.

Here is the syntax:

$variable = $value ?? $default;
  • $variable: The variable you want to check for null.
  • $value: The value to use if $variable is not null.
  • $default: The default value to use if $variable is null.

The following section provides an overview of how the null coalescing operator works. Let’s proceed.

How does the Null Coalescing Operator work?

This operation happens in one line. It makes the code easier to read and shorter than using regular if statements.

Here’s an example that shows you how it works:

// Using the null coalescing operator
$result = $variable ?? $default;

// Equivalent to
$result = isset($variable) ? $variable : $default;

The operator checks if the variable on the left side ($variable) is set and not null. If it is set and has a value, the result is the value of $variable. If $variable is not set or is null, the result is the value of $default.

This operator is very helpful when you work with user input, settings, or other cases where a variable could be null and you want to use a default value instead.

In the next section, you will see examples to help you understand how the null coalescing operator works in PHP.

Null Coalescing Operator Examples

Here is a basic example:

$username = $_GET['username'] ?? 'Guest';

In this example, we try to get the value of the username from the $_GET array. If the username exists and is not null, it will be saved in the $username variable.

But if username is null or does not exist, $username will get the value 'Guest'. This happens because of the null coalescing operator.

You can also chain the null coalescing operator to set default values for many variables.

Here is an example:

$username = $_GET['username'] ?? $_POST['username'] ?? 'Guest';

In this example, we try to get the username from the $_GET array. If it is null or not set, we then try to get it from the $_POST array. If that is also null or not set, $username will be set to 'Guest'.

The null coalescing operator is very useful when you work with arrays or objects in PHP.

Here is an example:

$person = [
    'name' => 'John',
    'age' => null,
    'country' => 'USA'
];

$age = $person['age'] ?? 'Unknown';

In this example, we try to get the age value from the $person array. But this key has a value of null. By using the null coalescing operator in PHP, we can set $age to 'Unknown' instead of null.

Also, it can work with functions. For example:

function getUserName() {
   return null;
}

$username = getUserName() ?? 'Guest';

In this example, we call the getUserName() function, which returns null. By using the null coalescing operator, we set $username to 'Guest' instead of null.

Chaining multiple fallback values dynamically:

$a = null;
$b = null;
$c = 'Value C';

$result = $a ?? $b ?? $c ?? 'Default';

Here is output:

Value C

This checks each variable in order and returns the first one that is not null.

Use an array access with null coalescing:

$data = [
    'name' => null,
    'email' => '[email protected]'
];

$name = $data['name'] ?? 'Unknown'; 
$email = $data['email'] ?? 'No Email';
$phone = $data['phone'] ?? 'No Phone';

Here is the output:

No Phone

So here you don’t need to use isset function, ?? does not emit a notice if the key doesn’t exist.

The Difference Between ?? and ?:

This operator “?:” Checks if $condition is truthy (not false, 0, "", null, []).
If it is, returns $valueIfTrue; otherwise, returns $valueIfFalse.

while Null Coalescing Operator (??) Checks if $value exists and is not null.
If $value is set and not null, it returns $value. Otherwise, it returns $default.

So, when do you use each one?

Use ??

  • When you care only about null or unset values.
  • Example: fallback defaults for variables that might not be set.

Use ?:

  • When you care about any falsy value (e.g., 0, '', false).
  • Example: choosing a label if a variable is empty or false.

Here is a table that shows you key differences:

OperatorChecks ForReturns Fallback If
??null/unsetVariable is not set or null
?:falsy valueVariable is falsy (0, ”, false, null, etc.)

Comparison with isset() and empty() in Null Coalescing Operator

How Null Coalescing Differs from isset() Checks:

The Null Coalescing Operator (??) is similar to isset function combined with the ternary syntax. But it has a simpler syntax.

Example with ??:

$value = $data['key'] ?? 'default';

This means: If $data['key'] exists and is not null, use it. Otherwise, use 'default'.

When you write:

$value = isset($data['key']) ? $data['key'] : 'default';

It does almost the same thing, but you must repeat $data['key'].

Here is the key difference:

  • isset() returns false if the variable is not set or is null.
  • ?? behaves the same way, but is shorter and cleaner.

How empty() Behaves Differently:

The empty() function checks more conditions. It returns true if the value is:

  • Not set,
  • null,
  • false,
  • 0 (integer or string),
  • '' (empty string),
  • [] (empty array).

For example:

$value = empty($data['key']) ? 'default' : $data['key'];

This means: If $data['key'] is missing or falsy, use 'default'.

Operator Precedence with Null Coalescing Operator

The null coalescing operator (??) has higher precedence than the logical OR operator (||). It has lower precedence than most other operators, but is higher than assignment (=).

For example:

$result = false ?? 'A' ?? 'B';

Since false is not null, $result is assigned false.

Be careful with mixing ?? and ||:

$result = false || null ?? 'A';

This is parsed as:

$result = false || (null ?? 'A');

Because ?? has higher precedence than ||.

  • null ?? 'A' evaluates to 'A'
  • Then false || 'A' evaluates to true

To control evaluation order, use parentheses:

$result = (false ?? 'X') || 'Y';

Or

$result = false ?? ('X' || 'Y');

Always use parentheses when combining ?? with ||, &&, or other operators to avoid confusion and ensure the correct order of evaluation.

Nested array access with chaining:

$user = [
    'profile' => [
        // 'bio' => 'Hello!'
    ]
];

$bio = $user['profile']['bio'] ?? 'No bio';
// $bio = 'No bio'

Output:

No bio

This does not show an error or a notice. It simply assigns the value if it exists; otherwise, it uses the default.

Version Compatibility and PHP Versions

The Null Coalescing Operator (??) was introduced in PHP 7.0. It does not work in PHP 5.x or older versions. If you try to use ?? in those versions, you’ll get a syntax error.

If your project must run on older PHP versions, you should use a ternary statement with isset() as a fallback.

This way gives you the same behavior without causing errors.

Wrapping UP

In this article, you learned what the null coalescing operator is and how it works. Here is a quick recap:

  • The null coalescing operator (??) was added in PHP 7.
  • It checks if a variable is set and not null. If it is, it uses that value. If not, it uses a default value.
  • The basic syntax looks like this: $variable = $value ?? $default;
  • You can chain it to check more than one value: $username = $_GET['username'] ?? $_POST['username'] ?? 'Guest';
  • It works well with arrays, objects, and function results.
  • It makes your code shorter and easier to read compared to if statements.

FAQs

What is the PHP null coalescing operator?

It is written as ??. It checks if a variable exists and is not null. If it is, it uses that value. If not, it returns a default value.

How does the null coalescing operator work in PHP?

It works by checking a variable on the left side. If the variable is set and not null, it returns that value. Otherwise, it returns the value on the right side as a default.

What is the syntax of the null coalescing operator?

The syntax is:
$variable = $value ?? $default;
Here, $value is checked first. If it is null, $default is used instead.

Can you chain the null coalescing operator?

Yes. You can chain it to check multiple variables or sources, like this:
$username = $_GET['username'] ?? $_POST['username'] ?? 'Guest';

When should I use the null coalescing operator?

Use it when you want to give a default value to a variable that might be null or not set. It is common with user input, settings, arrays, or function results.

Does the null coalescing operator work with functions?

Yes. It can handle function return values that might be null. For example:
$username = getUserName() ?? 'Guest';

Similar Reads

How to Remove the Last Character from a String in PHP

You may need to cut the last character from a string if it shows by mistake in PHP. That may…

PHP array_pop: Remove and Return the Last Element of an Array

The array_pop function in PHP gives you a direct way to take the last element from an array. Understand the…

PHP abs Function: How to Get Absolute Values

The abs() function in PHP gives you a number without its sign — it always returns a positive value. That…

PHP explode Function: How it Works with Examples

When you deal with text in PHP, sometimes you need to break it into parts. This is common when users…

PHP array_merge: Combine Multiple Arrays into One

You have two or more arrays. You want one. That is the problem array_merge solves in PHP. This function lets…

PHP strtoupper Function: Convert Strings to Uppercase

Use strtoupper() function when you want to change all letters in a string to uppercase in PHP. It works with…

File Handling in PHP

File Handling in PHP is an important tool especially when you need to manage files such as reading, writing, or…

PHP Spaceship Operator

If you are new to the PHP Spaceship Operator, then let me tell you, you're in for a treat. This…

PHP mb_strtolower: How to Handle Multibyte Strings Properly

The mb_strtolower() function in PHP turns every letter in a string into lowercase. It works with multibyte encodings like UTF-8.…

PHP Data Types: Understanding the 10 Primitive Types

The whole world of PHP programming revolves around data, be it numbers, text, or more complicated structures. Each of these…

Previous Article

Understanding the PHP Exclusive OR (XOR) Operator

Next Article

PHP Data Types: Understanding the 10 Primitive Types

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.