Please wait

Null Coalescing Operator

The null coalescing operator (??) in PHP is a shorthand way of checking if a value is "null", meaning it's either NULL or undefined, and if it is, providing a default value in its place. It can be used as a cleaner and more concise alternative to the ternary operator or conditional statement.

The result of $a ?? $b is:

  • if $a is defined, then $a,
  • if $a isn't defined, then $b.

Using the null coalescing operator

The basic syntax of the null coalescing operator is as follows:

$data = $someVariable ?? "Default value";

In this example, $someVariable is checked for a value. If it has a value that is not "null", it is assigned to $data. If $someVariable is "null", the default value "Default value" is assigned to $data.

The most common use case for this operator is to set a default value for a variable. For example:

echo $user ?? "Anonymous";

If the $user variable has a value, we can assume the user is logged in. Otherwise, we'll refer to the user as "Anonymous".

Exercise

Create a variable called $email. Its value should be $userEmail or a default value of false. Use the null coalescing operator.

Key takeaways

  • The null coalescing operator is written with the ?? characters.
  • PHP checks for a value on the left. If the value is not null or undefined, the value on the left will be returned.
  • Otherwise, the value on the right of the operator is returned.

Comments

Please read this before commenting