PHP Null Coalesce Operator

php-logo

In PHP7 the coalesce operator – ?? – will be introduced. It acts as a bit of syntactic sugar for the common case of needing to use a ternary in conjunction with isset().

The null coalesce operator returns its first operand if it exists and is not NULL; otherwise it returns its second operand. That indeed means that it won’t raise an E_NOTICE, and affords you to write shorter code:

// Fetches the request parameter user and results in 'nobody' if it doesn't exist
$username = $_GET['user'] ?? 'nobody';
// equivalent to: $username = isset($_GET['user']) ? $_GET['user'] : 'nobody';
 
// Calls a hypothetical model-getting function, and uses the provided default if it fails
$model = Model::get($id) ?? $default_model;
// 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;
// equivalent to: $width = isset($imageData['width']) ? $imageData['width'] : 100;

Looking forward to this one 🙂

PHP RFC: Null Coalesce Operator →

Did you know you can also omit the 2nd parameter from the ternary operator in PHP, since version 5.3? The expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Join the Conversation

4 Comments

Leave a comment

Leave a Reply to Bramus! Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.