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.
So it’s like JavaScript’s
||
operator. PHP is catching up 😉Also one of the first things that flashed through my mind 🙂
Yes, but has lots of thing. For detail you may refer at http://www.techflirt.com/null-coalescing-operator-php