Skip to content

PHP 7 – Null Coalesce Operator

One more new operator from glaring PHP7, couple of days back I wrote about php7 <=> spaceship operator , now I am going to write about “Null Coalesce Operator”.

The null coalescing operator is ??. There is no doubt at all it is going to be the most often used PHP operator in upcoming days.

It’s used to define a default value for null-able values. We can achieve the same output with ternary operator, ?: operator something like this – $_GET['key'] ?: "". However, this is not good practice, as if the value does not exist it will raise an E_NOTICE.To avoid this error , as of now we used some sort of isset() or ifsetor() operators .However this is unmanageable.

Null Coalesce Operator returns the left-hand operand if the operand is not null, Otherwise it returns the right operand.Left hand operand can contain a value, or it can be undefined.This means the $_GET[‘key’] ?? “” is completely safe and will not raise an E_NOTICE.

Examples :

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


$x = NULL;
$y = NULL;
$z = 3;
var_dump($x ?? $y ?? $z); // int(3)
 
$x = ["yarr" => "meaningful_value"];
var_dump($x["aharr"] ?? $x["waharr"] ?? $x["yarr"]); // string(16) "meaningful_value"

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)


function foo() {
    echo "executed!", PHP_EOL;
}
var_dump(true ?? foo()); // outputs bool(true), "executed!" does not appear as it short-circuited
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments