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?
This question is related to
php
conditional-operator
language-construct
Be careful with arrays. We must write a checking variable after ?
, because:
$params = ['param1' => 'value1',
'param2' => 'value2',
'param3' => 'value3',];
$param1 = isset($params['param1'])?:null;
$param2 = !empty($params['param2'])?:null;
$param3 = $params['param3']?:null; // get E_NOTICE, if $params['param3'] eq false
var_dump($param1,$param2,$param3);
true // would like to expect `value1`
true // would like to expect `value2`
param3 // properly, but problem above
Updated
From RFC. In PHP 7 the operator Null Coalesce Operator will do it, for example:
$param1 = $params['param1'] ?? null;
// Equivalent to: $param1 = isset($params['param1']) ? $params['param1'] : null;
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.
See the docs:
Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression
expr1 ?: expr3
returnsexpr1
ifexpr1
evaluates toTRUE
, andexpr3
otherwise.
?:
is the Elvis operator. This is a binary operator which does the following:
Coerces the value left of ?:
to a boolean and checks if it is true
. If true
it will return the expression on the left side, if false it will return the expression on the right side.
var_dump(0 ?: "Expression not true"); // expression returns: Expression not true
var_dump("" ?: "Expression not true"); // expression returns: Expression not true
var_dump("hi" ?: "Expression not true"); // expression returns string hi
var_dump(null ?: "Expression not true"); // expression returns: Expression not true
var_dump(56 ?: "Expression not true"); // expression return int 56
The Elvis operator is basically shorthand syntax for a specific case of the ternary operator which is:
$testedVar ? $ testedVar : $otherVar;
The Elvis operator will make the syntax more consise in the following manner:
$testedVar ?: $otherVar;
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!
Source: Stackoverflow.com