Quantcast
Channel: php – Bram.us
Viewing all articles
Browse latest Browse all 166

PHP Null Coalesce Operator

$
0
0

The coalesce operator – ?? – 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.


Viewing all articles
Browse latest Browse all 166

Trending Articles