PHP, Null Coalescing Operator

Earlier this month PHP 7.0.0 Alpha 1 was released. One item on the feature list caught my eye:

The null coalescing operator (??)

The background is at In short it “returns the result of its first operand if it exists and is not NULL, or else its second operand”. It does this without triggering E_NOTICE.

A short example:

[sourcecode lang=”php”]
$action = $_GET[‘action’] ?? ‘none’;

// The same as: $action = isset($_GET[‘action’]) ? $_GET[‘action’] : ‘none’;

I’m happy to see this make it into PHP 7.

First warning though, it may not always work the way you would expect it to. Specifically, $action = null ?? 'none'; results in $action being 'none'. But $action = false ?? 'none'; results in $action being false.

Second warning is that HHVM does not currently support the ?? operator. HHVM issue 4166 brings that up, but the last comment is from November 2014.

2 replies on “PHP, Null Coalescing Operator”

Leave a Reply

Your email address will not be published. Required fields are marked *