PHP 7 – Null Coalesce Operator

PHP 7 – Null Coalesce Operator

PHP 7 brings a lot of improvements, features and new operators as compared to the earlier versions on PHP. One of the new operators is the Null Coalesce Operator (??). This operator can be used instead of using isset() along with the ternary operator (?:).

The Null coalesce operator (??) returns the result of its first operand if it exists and is not NULL, or else it will return its second operand. Using this operator like $_GET[‘mykey’] ?? “” will not raise an E_NOTICE, and can be safely used.

So, instead of using isset and ternary operator (?:) we can just use the Null Coalesce Operator (??). Here is an example usage:

// 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';

We can also chain the Null Coalesce operator. Here is an example:

// This will return the first defined value out of 
// $_GET['user'], $_POST['user'], and 'nobody'.
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';

More examples and difference from ternary operator

// This will make the value of $action to be 'none'.
// This is because the first operand is null.
$action = null ?? 'none'; 

// Ternary Operator, value will be 12
$action = false ?:  12;
// Null Coalesce Operator, value will be false. 
// This is because the first operator exists and is not null.
$action = false ?? 'none';

Here are a few more examples from PHP RFP for Null Coalesce Operator

// Calls a hypothetical model-getting function,
// and uses the provided default if it fails
$model = Model::get($id) ?? $default_model;
// This is equivalent to: 
if (($model = Model::get($id)) === NULL) { $model = $default_model; }
 
// Parse JSON image metadata, and
// if the width is missing, assume 100
$imageData = json_decode(file_get_contents('php://input'));
$width = $imageData['width'] ?? 100;
// This is equivalent to:
$width = isset($imageData['width']) ? $imageData['width'] : 100;

This example demonstrates the precedence relative to the ternary operator and the boolean or operator, which is the same as C#:

var_dump(2 ?? 3 ? 4 : 5);      // (2 ?? 3) ? 4 : 5        => int(4)
var_dump(0 || 2 ?? 3 ? 4 : 5); // ((0 || 2) ?? 3) ? 4 : 5 => int(4)

More reading:
PHP RFC: Null Coalesce Operator

Leave a Reply