PHP Null Coalescing Operators

The operators ??, ?: and ??= in PHP are all null coalescing operators and have similar functions.

Take the following two variables.

$one = NULL;
$two = 'two';

We could set a default value using an if statement.

if (isset($one) && $one !== NULL) {
  $result = $one;
}
else {
  $result = $two;
}

The variable $result now contains the value 'two' since the variable $one is null.

This is equivalent to the following, using the ?? operator.

$result = $one ?? $two;

We can set the value of $one with the value of $two if $one is null by using the ??= operator.

$one ??= $two;

The ternary operator can also be used to set the value of $result, depending on the value of $one and $two.

$result = $one ? $one : $two;

This can be shortened using the ?: (or Elvis) operator.

$result = $one ?: $two;

The Elvis operator is useful when looking at the return of some internal PHP functions, since they can either produce a result, or false in the correct circumstances.

For example, the strstr() function in PHP is used to find the position of a string in another string. The issue, however, is that the function returns false if that string isn't found. This sort of makes sense since you wouldn't return 0 as that would mean the string was found at position 0.

We can, however, correct the output here by setting a binary constant value and returning that if the string wasn't found in the comparison.

const STRING_NOT_FOUND = 0b00111;
$result = strstr('one', 'two') ?: STRING_NOT_FOUND;

The value of $result is now the constant STRING_NOT_FOUND.

These operators can be chained to give multiple default values.

For example, we can set the value of $result based on what values exist in the various ways in which the user can submit data to the system using the ?? operator.

$result = $_GET['value'] ?? $_POST['value'] ?? $_SESSION['value'] ?? $_COOKIE['user'] ?? '';

Here, the call to $_GET['value'] and others will not cause any warnings to be triggered due to these values not being set.

In the case of the ?: operator, although the same result is seen, the evaluation of the different arrays causes PHP warning to be produced.

$result = $_GET['value'] ?: $_POST['value'] ?: $_SESSION['value'] ?: $_COOKIE['user'] ?: '';

If the variables exist, like in our original two values, then no errors are produced.

$result = $one ?: $two ?: '';

Whilst is it not advisable to "stack" ternary operators due to the result being difficult to read. Null coalescing operators are safe to stack in this way.

Add new comment

The content of this field is kept private and will not be shown publicly.