The PHP null coalescing operator (??) is a new feature of PHP7. The purpose of this feature to allow you set a primary default value if main operand display undefined or null value.

PHP Null Coalescing Operator

The PHP null coalescing operator uses this this operator “??” between the default value and the potential value for the operation.

For example.

  $username = $_GET["username"] ?? "undefined Username.";
  echo $username;


The output of the previous example would be “undefined Username” because the global variable $_GET already not found.

There is an equivalent different way for this operation, you can use the inline if statement. For example.

  $username = isset( $_GET["username"] )? $_GET["username"] : "undefined Username.";
  echo $username;


It will print the same result.

Anyway, PHP allows you to use unlimited null coalescing operators in the same line. Let’s see an example.

  $name = $_GET["a"] ?? $_GET["b"] ?? $_GET["c"] ?? $_GET["d"] ?? $_GET["e"] ?? "undefined name";
  echo $name;


In this example the result would be “undefined name” because there is no value or defined variable there.
But, how it does work if two or more variables already had values ?

Let’s see that.


  $_REQUEST["b"] = "Name B";
  $_REQUEST["e"] = "Name E"; 
  $_REQUEST["d"] = "Name D";
  $name = $_REQUEST["a"] ?? $_REQUEST["b"] ?? $_REQUEST["c"] ?? $_REQUEST["d"] ?? $_REQUEST["e"] ?? "Undefined Name";
  echo $name; // Name B

As you saw, it printed the first global variable in the stack. So it is working according to the priority. The $_REQUEST["b"] taking a high priority in the null coalescing operator.

Wrapping UP

In this article, you understood what PHP null coalescing operator is and how it does work also I exposed that with examples.

Thank you for reading, to lean more detail visit PHP manual. Anyway, stay tuned for my next articles.