?: operator in PHP undocumented behaviour

Question

I was looking for an operation similar to javascript's || assignment operation:

foo = getFoo();
const bar = foo || 'default';

alice will equal foo unless it's equal to false, then it'll get the default value.

in PHP it's seems this operator (??) was added in PHP7

http://php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op

The guide for php5 says to write the code like this:

$foo = getFoo();
$bar = $foo ? $foo : 'default';

This is repetitive and looks bad. We have to write $foo twice.

By accident i've stumbled upon the (?:) operator, and this code seems to work:

$foo = getFoo();
$bar = $foo ?: 'default';

This actually seem to work: https://www.tehplayground.com/7ut74LTXkEFsSvLF

but it's not stated in any official guide or place. I am afraid i've either ran into a bug or this won't be supported on different versions of PHP. Does anyone have additional information on this operator?


Show source
| php   2017-01-03 16:01 2 Answers

Answers to ?: operator in PHP undocumented behaviour ( 2 )

  1. 2017-01-03 16:01

    It is in fact documented. Scroll down to the section titled Ternary Operator

    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.

  2. 2017-01-03 16:01

    It's documented here: Ternary operator

    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.

    BTW, it's not easy to find.

Leave a reply to - ?: operator in PHP undocumented behaviour

◀ Go back