I saw this today in some PHP code:
$items = $items ?: $this->_handle->result('next', $this->_result, $this);
I'm not familiar with the ?:
operator being used here. It looks like a ternary operator, but the expression to evaluate to if the predicate is true has been omitted. What does it mean?
Yes, this is new in PHP 5.3. It returns either the value of the test expression if it is evaluated as TRUE, or the alternative value if it is evaluated as FALSE.
It evaluates to the left operand if the left operand is truthy, and the right operand otherwise.
In pseudocode,
roughly resolves to
or
with the difference that
bar
will only be evaluated once.You can also use this to do a "self-check" of
foo
as demonstrated in the code example you posted:This will assign
bar
tofoo
iffoo
is null or falsey, else it will leavefoo
unchanged.Some more examples:
By the way, it's called the Elvis operator.
See the docs:
Another important consideration: The Elvis Operator breaks the Zend Opcache tokenization process. I found this the hard way! While this may have been fixed in later versions, I can confirm this problem exists in PHP 5.5.38 (with in-built Zend Opcache v7.0.6-dev).
If you find that some of your files 'refuse' to be cached in Zend Opcache, this may be one of the reasons... Hope this helps!
Be careful with arrays. We must write a checking variable after
?
, because:Updated
From RFC. In the future (in PHP 7) operator Null Coalesce Operator will do it, for example: