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?
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.