From the docs:

Coalesce equal or ??=operator is an assignment operator. If the left parameter is null, assigns the value of the right parameter to the left one. If the value is not null, nothing is done.

Example:

// The following lines are doing the same
$this->request->data['comments']['user_id'] = $this->request->data['comments']['user_id'] ?? 'value';
// Instead of repeating variables with long names, the equal coalesce operator is used
$this->request->data['comments']['user_id'] ??= 'value';

So it's basically just a shorthand to assign a value if it hasn't been assigned before.

Answer from Pavel Lint on Stack Overflow
🌐
PHP Tutorial
phptutorial.net › home › php tutorial › php null coalescing operator
PHP Null Coalescing Operator
June 25, 2021 - The following example uses the null coalesing operator to assign the 0 to $counter if it is null or doesn’t exist: ... The above statement repeats the variable $counter twice. To make it more concise, PHP 7.4 introduced the null coalescing assignment operator (??=):
🌐
PHP
php.net › manual › en › migration70.new-features.php
PHP: New features - Manual
$username = $_GET['user'] ?? 'nobody'; // This is equivalent to: $username = isset($_GET['user']) ? $_GET['user'] : 'nobody'; // Coalescing can be chained: this will return the first // defined value out of $_GET['user'], $_POST['user'], and ...
🌐
Tutorialspoint
tutorialspoint.com › home › php › php null coalescing operator
PHP Null Coalescing Operator
May 26, 2007 - A useful application of Null Coalescing operator is while checking whether a username has been provided by the client browser. The following code reads the name variable from the URL. If indeed there is a value for the name parameter in the URL, a Welcome message for him is displayed. However, if not, the user is called Guest. <?php $username = $_GET['name'] ??
🌐
Stitcher
stitcher.io › blog › php-8-nullsafe-operator
PHP 8: the null safe operator | Stitcher.io
The null coalescing operator is actually an isset call in disguise on its lefthand operand, which doesn't support short circuiting. Short circuiting also means that when writing something like this: ... Join over 14k subscribers on my mailing list: I write about PHP, programming, and keep you up to date about what's happening on this blog.
🌐
Educative
educative.io › answers › what-is-a-null-coalescing-operator-in-php
What is a null coalescing operator in PHP?
Before the inclusion of null coalescing operator in PHP, null checking was done by using ternary operator or if-else statement was used in conjunction with isset() function. In the following three examples, if $_GET['user'] is set and not null, $_GET['user'] will be assigned to $user.
🌐
Rip Tutorial
riptutorial.com › null coalescing operator (??)
PHP Tutorial => Null Coalescing Operator (??)
Note: When using coalescing operator on string concatenation dont forget to use parentheses () $firstName = "John"; $lastName = "Doe"; echo $firstName ?? "Unknown" . " " . $lastName ?? ""; This will output John only, and if its $firstName is ...
🌐
Linux Hint
linuxhint.com › null_coalescing_php
How to use PHP Null Coalescing Operator – Linux Hint
The null coalescing operator can be used with two or more variables. In this example, the operator is used to check the values of different variables. <?php //Define two variables $var1 = 'This is the first string value.'; $var3 = 'This is the third string value.'; $var4 = NULL; $var5 = 'This ...
🌐
PHP
wiki.php.net › rfc › null_coalesce_equal_operator
PHP RFC: Null Coalescing Assignment Operator
// The folloving lines are doing the same $this->request->data['comments']['user_id'] = $this->request->data['comments']['user_id'] ?? 'value'; // Instead of repeating variables with long names, the equal coalesce operator is used $this->request->data['comments']['user_id'] ??= 'value';
Find elsewhere
🌐
Steemit
steemit.com › utopian-io › @gentlemanoi › php7-how-to-use-null-coalescing-operator
PHP7 : How to use Null Coalescing Operator — Steemit
February 8, 2018 - The difference between this two operators is that the null coalescing operator evaluates the first operand if it is null. It's like using the isset() function. While the ternary operator evaluates the first operand as a boolean expression. Examples: <?php $a = ''; $b = 'String B'; echo $a ??
Top answer
1 of 14
645
  • Elvis ?: returns the first argument if it contains a "true-ish" value (see which values are considered loosely equal to true in the first line of the Loose comparisons with == table). Or the second argument otherwise

      $result = $var ?: 'default';
      // is a shorthand for 
      $result = $var ? $var : 'default';
    
  • Null coalescing ?? returns the first argument if it's set and is not null. Or the second argument otherwise

      $result = $var ?? 'default';
      // is a shorthand for 
      $result = isset($var) ? $var : 'default';
    

When your first argument is null, they're basically the same except that the null coalescing won't output an E_NOTICE when you have an undefined variable. The PHP 7.0 migration docs has this to say:

The null coalescing operator (??) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

Here's some example code to demonstrate this:

<?php

$a = null;

print $a ?? 'b'; // b
print "\n";

print $a ?: 'b'; // b
print "\n";

print $c ?? 'a'; // a
print "\n";

print $c ?: 'a'; // Notice: Undefined variable: c in /in/apAIb on line 14
print "\n";

$b = array('a' => null);

print $b['a'] ?? 'd'; // d
print "\n";

print $b['a'] ?: 'd'; // d
print "\n";

print $b['c'] ?? 'e'; // e
print "\n";

print $b['c'] ?: 'e'; // Notice: Undefined index: c in /in/apAIb on line 33
print "\n";

The lines that have the notice are the ones where I'm using the shorthand ternary operator as opposed to the null coalescing operator. However, even with the notice, PHP will give the same response back.

Execute the code: https://3v4l.org/McavC

Of course, this is always assuming the first argument is null. Once it's no longer null, then you end up with differences in that the ?? operator would always return the first argument while the ?: shorthand would only if the first argument was truthy, and that relies on how PHP would type-cast things to a boolean.

So:

$a = false ?? 'f'; // false
$b = false ?: 'g'; // 'g'

would then have $a be equal to false and $b equal to 'g'.

2 of 14
271

Ran the below on php interactive mode (php -a on terminal). The comment on each line shows the result.

var_export (false ?? 'value2');   // false
var_export (true  ?? 'value2');   // true
var_export (null  ?? 'value2');   // value2
var_export (''    ?? 'value2');   // ""
var_export (0     ?? 'value2');   // 0

var_export (false ?: 'value2');   // value2
var_export (true  ?: 'value2');   // true
var_export (null  ?: 'value2');   // value2
var_export (''    ?: 'value2');   // value2
var_export (0     ?: 'value2');   // value2

The Null Coalescing Operator ??

  • ?? is like a "gate" that only lets NULL through.
  • So, it always returns first parameter, unless first parameter happens to be NULL.
  • This means ?? is same as ( !isset() || is_null() )

Use of ??

  • shorten !isset() || is_null() check
  • e.g $object = $object ?? new objClassName();

Stacking Null Coalese Operator

        $v = $x ?? $y ?? $z; 

        // This is a sequence of "SET && NOT NULL"s:

        if( $x  &&  !is_null($x) ){ 
            return $x; 
        } else if( $y && !is_null($y) ){ 
            return $y; 
        } else { 
            return $z; 
        }

The Ternary Operator ?:

  • ?: is like a gate that lets anything falsy through - including NULL
  • Anything falsy: 0, empty string, NULL, false, !isset(), empty()
  • Same like old ternary operator: X ? Y : Z
  • Note: ?: will throw PHP NOTICE on undefined (unset or !isset()) variables

Use of ?:

  • checking empty(), !isset(), is_null() etc
  • shorten ternary operation like !empty($x) ? $x : $y to $x ?: $y
  • shorten if(!$x) { echo $x; } else { echo $y; } to echo $x ?: $y

Stacking Ternary Operator

        echo 0 ?: 1 ?: 2 ?: 3; //1
        echo 1 ?: 0 ?: 3 ?: 2; //1
        echo 2 ?: 1 ?: 0 ?: 3; //2
        echo 3 ?: 2 ?: 1 ?: 0; //3
    
        echo 0 ?: 1 ?: 2 ?: 3; //1
        echo 0 ?: 0 ?: 2 ?: 3; //2
        echo 0 ?: 0 ?: 0 ?: 3; //3

    
        // Source & Credit: http://php.net/manual/en/language.operators.comparison.php#95997
   
        // This is basically a sequence of:

 
        if( truthy ) {}
        else if(truthy ) {}
        else if(truthy ) {}
        ..
        else {}

Stacking both, we can shorten this:

        if( isset($_GET['name']) && !is_null($_GET['name'])) {
            $name = $_GET['name'];
        } else if( !empty($user_name) ) {
             $name = $user_name; 
        } else {
            $name = 'anonymous';
        }

To this:

        $name = $_GET['name'] ?? $user_name ?: 'anonymous';

Cool, right? :-)

🌐
Stitcher
stitcher.io › blog › shorthand-comparisons-in-php
Shorthand comparisons in PHP | Stitcher.io
The null coalescing operator is used to provide default values instead of null · The spaceship operator is used to compare two values
Top answer
1 of 1
3

The key issue here is operator precedence. In PHP, both the cast operator (int) and the comparison operator < have a higher precedence than the null coalescing operator ??. This means that in your first example

((int)$var['x']??0 < 1 )

PHP interprets the expression as if you had written:

(((int)$var['x']) ?? (0 < 1))

Here’s what happens step-by-step:

  1. Casting: (int)$var['x'] is evaluated first, converting the string "5" to the integer 5.

  2. Comparison: The < operator is evaluated next. Since < has a higher precedence than ??, the expression 0 < 1 is computed, yielding true.

  3. Null Coalescing: Now PHP evaluates 5 ?? true. Because 5 is not null, the result of the null coalescing operator is 5.

  4. Condition Check: In an if statement, a non-zero number is truthy, so the condition evaluates as true, and "less than 1" is printed.

In Example 2, a similar misinterpretation occurs:

($var['x']??5 < 1 )

This is interpreted as:

($var['x'] ?? (5 < 1))

Since $var['x'] is "5" (a non-null value), the null coalescing operator returns "5". In PHP, a non-empty string (other than "0") is truthy, so the condition is true, and "less" is printed.

In Example 3, you force the intended order by adding parentheses.

((int)($var['x']??0) < 1 )

Here, the expression inside the parentheses $var['x']??0 is evaluated first. Since $var['x'] exists, it returns "5", which is then cast to 5. The comparison 5 < 1 correctly evaluates to false, so "more than 1" is printed.

The unexpected behavior arises because without the proper grouping, PHP evaluates the cast and the comparison before applying the null coalescing operator. Adding explicit parentheses clarifies the order of operations and ensures the expression evaluates as intended.

🌐
FlatCoding
flatcoding.com › home › php null coalescing operator: handling null values
PHP Null Coalescing Operator: Handling Null Values - FlatCoding
June 30, 2025 - 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.
🌐
Markshust
markshust.com › 2017 › 08 › 25 › php-7s-null-coalesce-operator-usage-objects-and-arrays
PHP 7's null coalesce operator usage with Objects and Arrays | Mark Shust
<?php class Foo {} $foo = new Foo; echo isset($foo) && isset($foo->b) && isset($foo->b->c) ? $foo->b->c : 'baz'; You can see how it can easily become a handful when working with many object properties.
🌐
Benjamin Crozat
benjamincrozat.com › home › blog › php › php's double question mark, or the null coalescing operator
PHP's double question mark, or the null coalescing operator
September 28, 2025 - Example pattern: $greeting = 'Hi ' . ($name ?? 'friend');. See the operator precedence list for details (reference). With arrays or user input, prefer ?? to avoid an undefined index notice. This is a clean alternative to isset(...) checks (think “isset vs null coalescing”). If you are on PHP 8.0+, also look at the nullsafe operator for safe property access.
🌐
sebhastian
sebhastian.com › null-coalescing-operator-php
The PHP null coalescing operator (??) explained | sebhastian
July 11, 2022 - The operator will go from left to right looking for a non-null value: $user = $username ?? $first_name ?? $last_name ?? 'nathan'; echo $user; // 'nathan'; When the value of $username is null or not set, PHP will look for the value of $first_name.
🌐
Reddit
reddit.com › r/phphelp › does php 7.2 and up support null coalescing operators that nullify exceptions?
r/PHPhelp on Reddit: Does PHP 7.2 and up support null coalescing operators that nullify exceptions?
November 3, 2021 -

Hi,

There are really two questions - at some point in programming PHP these past 2 years I started avoiding the null coalescing operator (??), but I don’t really know why since they all use 7.2 and the docs say the operator is available starting in 7.0.

Is the null coalescing operator safe in 7.2 and up?

Will it store null if there’s an exception generated, especially indexing a nested array and trying to Index on null or undefined?

Does isset() catch exceptions and return null as well? Or will it throw an exception?

Thanks!

Top answer
1 of 7
3
I believe you have some fundamental misunderstanding of a few things. The only way to catch exceptions is with catch. Exceptions are errors, so it wouldn't make sense for the null coalescing operator—which returns some value if the left-hand value is null—to magically suppress it. It also wouldn't make sense for the null coalescing operator to assume something is null if an exception occurred. Why would it? See here . Notice how the exception basically kills everything. That's supposed to happen because it means something went wrong, not that something went null. According to the PHP docs , "the program will terminate with a fatal error" if an unhandled exception occurs. Now look here . In this case, the exception was handled and the code continued as normal. At no point does the exception stop execution, at no point is null somehow returned. It's totally unrelated. If you're getting exceptions in general, you need to be handling them because they mean an error occurred that should not have occurred. That means either A) using catch, not to suppress them, but to handle them and do whatever needs to be done (for example, displaying a pretty error message), or B) rewriting whatever portion of your code allowed the exception to be thrown in the first place such that it will never happen again. So, to answer your two questions... no, PHP 7.2 does not support null coalescing operators that "nullify" exceptions, and it never will. However, yes, null coalescing operators are safe to use.
2 of 7
1
The ternary operator is a short replacement for simple if statements like this: if ($var) { } else { } Which matches whether the result of $var is true or false, whereas the null coalescing operator tests on not NULL and is a short replacement for: if (!is_null($var)) { } else { } A common gotcha in PHP is what contributes to a NULL value. You can set a string to "", and to empty() this returns true just the same as the value not defined or set to NULL. However, isset() checks to see if the variable is set and not NULL, and "" is not NULL, so it returns true, is_null does the opposite, returning "" as false. gettype() returns a string if the variable contains "" and empty() returns true in all three cases with boolean returning false in all three cases. If you know there will be an exception use break to break out of the loop before the exception occurs. You can specify the depth of the loop you wish to break out of, so a break 2; will break out of a nested loop that consists of two loops. You can test for exceptions by putting the code you suspect will cause an exception in the try block, then return the exception from the catch block and optionally, run code after from the finally block.
🌐
dailycomputerscience
dailycomputerscience.com › post › php-8-null-coalescing-operator
PHP 8 Null Coalescing Operator
October 5, 2024 - Without the null coalescing operator, you would need several isset() calls to ensure that none of the intermediate array keys are undefined. PHP 7.4 introduced the null coalescing assignment operator (??=), which allows you to assign a value to a variable only if it is null.