views:

373

answers:

3
+15  Q: 

?: operator PHP

I saw this today in some PHP code.

$items = $items ?: $this->_handle->result('next', $this->_result, $this);

What is the ?: doing? Is it a Ternary operator without a return true value? A PHP 5.3 thing?

I tried some test code but got syntax errors.

+16  A: 

See the docs

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

Yacoby
Thanks for that ;]
alpha_juno
They need a new doc writer because inevitably somebody will ask what happened to expr2. I just thunk it.
John K
+1  A: 

Yes, this is new in PHP 5.3. It returns either the result of the boolean test value if it is evaluated as TRUE, or the alternative value if it is evaluated as FALSE.

Atli
+13  A: 

It's by the way called the Elvis operator. It does an implicit nullcheck on the lefthand and only assigns it when it is not null, else it will assign the righthand.

In pseudocode,

foo = bar ?: baz;

roughly resolves to

foo = (bar != null) ? bar : baz;

or

if (bar != null) {
    foo = bar;
} else {
    foo = baz;
}

You can also use this to do a "self-check" of foo as demonstrated in the code example you posted:

foo = foo ?: bar;

This will assign bar to foo when foo is null, else it will keep the foo "intact".

BalusC
+1 For the code explanation :)
AntonioCS
Excellent thanks ;]
alpha_juno
+1 for the king reference LOL
Elzo Valugi