C#’s null coalescing operator (??) in PHP

PHP 7 adds the null coalescing operator:

// Fetches the value of $_GET['user'] and returns 'nobody'
// if it does not exist.
$username = $_GET['user'] ?? 'nobody';
// This is equivalent to:
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';

You could also look at short way of writing PHP’s ternary operator ?: (PHP >=5.3 only)

// Example usage for: Short Ternary Operator
$action = $_POST['action'] ?: 'default';

// The above is identical to
$action = $_POST['action'] ? $_POST['action'] : 'default';

And your comparison to C# is not fair. “in PHP you have to do something like” – In C# you will also have a runtime error if you try to access a non-existent array/dictionary item.

Leave a Comment