PHP Null Coalesce Operator


In PHP7 the coalesce operator – ?? – will be introduced. When used it returns the result of its first operand if it exists and is not NULL, or else 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.

Join the Conversation


Leave a comment

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.