https://github.com/phpstan/phpstan-strict-rules has a rule disallowing empty. I like the rule and although I haven't used this ruleset I try to avoid using empty in PHP. An undefined variable is empty, but how often do you want to write code that references a variable that may not exist? I basically never do except by mistake, and when I make that mistake I'd like my static analysis tools to tell me. If I've used empty where I mean x === '' $x || === null then they can't do that. Answer from czbz on reddit.com
🌐
PHP Delusions
phpdelusions.net › articles › null_coalescing_abuse
Do you abuse the null coalescing operator (and isset/empty as well)? - Treating PHP Delusions
Thank you so much for your helpful instructions. This is the best website for php, pdo and mysql you can find! It helped to improve my coding a lot. ... Well, to be fair, any modern IDE will tell you if you have an undefined variable. But you are right about empty().
🌐
Reddit
reddit.com › r/php › has there been any talk of an "empty" coalesce operator?
r/PHP on Reddit: Has there been any talk of an "empty" coalesce operator?
February 8, 2023 -

I'm a big fan of null coalesce, but I want more. There are definitely times where I want to set a default value if a variable is "empty". Perl has two coalesce operators:

$num ||= 8; # Empty coalesce
$num //= 8; # null/undef coalesce

Any chance PHP will get any sort of empty coalesce operator? Right now I'm writing out:

if (empty($num)) { $num = 8; }

which is a lot more typing, not chainable, and less readable? It'd be really nice to be able to do something like:

$num = $cost ||| $prev_num ||| $default_val;

Where ||| is the operator I made up for empty coalesce.

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

        x ?? 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 : $y to y
  • shorten if(!$x) { echo $x; } else { echo $y; } to echo 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? :-)

People also ask

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.
🌐
flatcoding.com
flatcoding.com › home › php null coalescing operator: handling null values
PHP Null Coalescing Operator: Handling Null Values - FlatCoding
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.
🌐
flatcoding.com
flatcoding.com › home › php null coalescing operator: handling null values
PHP Null Coalescing Operator: Handling Null Values - FlatCoding
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.
🌐
flatcoding.com
flatcoding.com › home › php null coalescing operator: handling null values
PHP Null Coalescing Operator: Handling Null Values - FlatCoding
🌐
PHP
php.net › manual › en › migration70.new-features.php
PHP: New features - Manual
It returns its first operand if it exists and is not null; otherwise it returns its second operand. <?php // Fetches the value of $_GET['user'] and returns 'nobody' // if it does not exist. $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 // 'nobody'.
🌐
Scito
scito.ch › content › php-isset-vs-empty-vs-isnull-vs-ifvar-vs-null-coalesce
PHP isset() vs empty() vs is_null() vs if($var) vs null coalesce (??) | Scito
\'-\'<br>Null Coalesce Operator (since PHP 7.0)</th>'; echo '</tr>'; echo '</thead>'; echo '<tbody>'; $var = ''; echo '<tr><td>"" (an empty string)</td><td>'; var_dump(isset($var)); echo '</td><td>'; var_dump(empty($var)); echo '</td><td>'; var_dump(is_null($var)); echo '</td><td>'; echo ($var) ?
🌐
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 null coalescing operator (??) will check if the first operand is set or not NULL. If it is not NULL, then it will return the value of the first operand. Otherwise, it will return the value of the second operand. ... This example will output 'String A' because variable $a has a value.
🌐
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
🌐
FlatCoding
flatcoding.com › home › php null coalescing operator: handling null values
PHP Null Coalescing Operator: Handling Null Values - FlatCoding
June 30, 2025 - The Null Coalescing Operator (??) is similar to isset function combined with the ternary syntax. But it has a simpler syntax. ... This means: If $data['key'] exists and is not null, use it. Otherwise, use 'default'. ... It does almost the same thing, but you must repeat $data['key']. ... The empty() function checks more conditions.
Find elsewhere
🌐
Tutorialspoint
tutorialspoint.com › home › php › php null coalescing operator
PHP Null Coalescing Operator
May 26, 2007 - Let us use the ternary operator to check if a certain variable is set or not with the help of the isset() function, which returns true if declared and false if not. <?php $x = 1; $var = isset($x) ? $x : "not set"; echo "The value of x is $var"; ?> ... The Null Coalescing Operator is represented by the "??" symbol.
🌐
Sipponen
sipponen.com › archives › 4328
PHP and Null Coalescing Operator | SIPPONEN.COM
October 2, 2024 - I always try to generate as readable HTML as possible, and therefore I try to inject new lines with PHP when it makes sense from HTML point of view, even it is not visible for the end user. 30.7.2024 update: You can even chain multiple Null Coalescing Operators together: $your_var = $_GET['your_var'] ?? $_POST['your_var'] ?? ''; Above will first try to get your_var from GET inputs, if not succeeding, then trying to get that from POST inputs and very last uses empty string if POST input was not available.
🌐
PHP Tutorial
phptutorial.net › home › php tutorial › php null coalescing operator
PHP Null Coalescing Operator
June 25, 2021 - <?php $name = $_POST['name'] ?? 'John';Code language: PHP (php) In this example, the ?? is the null coalescing operator. It accepts two operands. If the first operand is null or doesn’t exist, the null coalescing operator returns the second operand. Otherwise, it returns the first one. In the above example, if the variable name doesn’t exist in the $_POST array or it is null, the ?? operator will assign the string 'John' to the $name variable.
🌐
GitHub
github.com › smarty-php › smarty › issues › 882
Support the null coalescing operator · Issue #882 · smarty-php/smarty
April 30, 2023 - One might argue that it is not required, since the default modifier largely serves the same purpose. However, the default modifier is also triggered by an empty string: '', whereas the null coalescing operator would only replace a null value ...
Published   Apr 30, 2023
🌐
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 is the fifth string value.'; $var6 = ''; //Check the value of the variables $result1 = $var1 ??
🌐
Uptimia
uptimia.com › home › questions › what's the difference between php's elvis (?:) and null coalescing (??) operators?
What's The Difference Between PHP's Elvis (?:) And Null Coalescing (??) Operators?
October 27, 2024 - Elvis operator: Returns the second argument for falsy values (0, empty string, false). Null coalescing operator: Returns the first argument if it's set, even if it's falsy. These differences make each operator useful for specific scenarios in ...
🌐
Remicorson
remicorson.com › the-null-coalescing-operator-and-the-ternary-operator-in-php
The Null Coalescing Operator ?? and The Ternary Operator ?: in ...
Those two operators give a way to write more concise code and shorten expressions used in PHP. ... Basically, this operator will return the first non NULL value. This structure will return $value1 if it’s not NULL or $value2: ... if( isset( $_GET['my_variable'] ) && !is_null( $_GET['my_variable'] ) ) { $my_variable = $_GET['my_variable']; } else if( !empty( $my_defined_variable ) ) { $my_variable = $my_defined_variable; } else { $my_variable = 'whatever'; }
🌐
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 null and $lastName is Doe it will output Unknown Doe.
🌐
dailycomputerscience
dailycomputerscience.com › post › php-8-null-coalescing-operator
PHP 8 Null Coalescing Operator
October 5, 2024 - PHP 7.4 introduced the null coalescing assignment operator (??=), which allows you to assign a value to a variable only if it is null. $username = null; $username ??= 'Guest'; echo $username; // Outputs: Guest · In this case, if $username is ...
🌐
SitePoint
sitepoint.com › php
Null Coalescing Operator equivalent for object property - PHP - SitePoint Forums | Web Development & Design Community
February 10, 2022 - Hello. I’m currently following through the PHP Novice to Ninja book, and adapting it for a blog website. I have potential problem if a user account is deleted and I’m wondering how I might do the equivalent of a null coalescecing operator on the following name property of a comment object:
🌐
Global Open Versity
lms.lamaiedu.com › articles › how-to-use-php-null-coalescing-operator
How to use PHP Null Coalescing Operator - Global Open Versity
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 is the fifth string value.'; $var6 = ''; //Check the value of the variables $result1 = $var1 ??