Snippet: Using ?? / Null coalescing operator in PHP 7

Welcome to Snippets! Like most I struggle to publish blog posts regularly, so I’ve decided to publish short snippets whenever I have a “why on earth didn’t I know this / do this sooner?” moment.

Working with client sites I tend to be very conservative in my use of new features as I don’t control on which server my code runs. But the downside is that I then overlook new features once the PHP version becomes safe to assume as baseline.

This happened with PHP7 and the null coalescing operator. It’s a small improvement but given how often I have to check if a variable isset() it’s a small but valuable operator to keep my code concise.

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.

From https://www.php.net/manual/en/migration70.new-features.php
<?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'.
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
?>

One downside is that I tend to set variables as empty and then use empty() to check on it. Going forward I can see a case for setting a variable to NULL when initiating so I can use the ?? operator to see if it conains a value.

JavaScript / Short Circuit Evaluation

Thinking about checking if a variable is set, a similar concept exists in JS with “Short Circuit Evaluation”: https://en.wikipedia.org/wiki/Short-circuit_evaluation where the last value is assigned if the values before are falsey. See also the StackOverflow discussion here for more explanations: https://stackoverflow.com/questions/2100758/javascript-or-variable-assignment-explanation#2100767.

// Assigns the variable if not falsey, otherwise sets it to an empty array
var myData = data || {}; 

Leave a Comment

Your email address will not be published. Required fields are marked *