PHP Ternary Operator – Using PHP’s Ternary Operator with Two Arguments

comparisonoperatorsPHP

I was recently reviewing some of my code and noticed that in a fit of absent-mindedness, I'd left a structure like the following:

$guid = empty($subscription->guid) ?  : $subscription->guid;

Now, this wasn't doing what it's supposed to and is wrong, but since that property is always set now it was working fine, and there's no syntax error since 5.3 because of the following change:

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.

I wasn't aware of this change, and now I'm curious if I should be using it or not. This is something I was sorely missing from languages like ruby where you can do eg, a = b || c to get either b or c rather than a 'real' boolean. However, the syntax they've chosen for the ternary operator seems a little counter intuitive to me. Should I be using this in production code? It definitely threw myself when I saw it by accident.

Best Answer

The ternary conditional operator without the second argument is a bit novel, but it is similar1 to the null-coalescing operator found in other Algol-derivative languages like C# and Perl, and as you mention, the || operator in Ruby (and JavaScript).

It looks weird at first, but it's not too out there (especially since there's precedent for similar operators in other languages), and can save a good deal of keystrokes. And, if what happened with the namespace delimiter (\) is any indication, weird syntaxes will eventually be adopted by the PHP community.

But one of the major problems PHP applications tend to face is the (sometimes) excruciatingly long lag time between release of a new version of PHP and when hosts start to support it. This leads to issues where you need to be backwards compatible with older versions of PHP, forgoing the use of convenience changes like this.

If that's not a concern to you, and your team agrees on its usage (or if you're a solo developer, if you're comfortable with it), by all means go for it. Like the namespace delimiter, I really think it's really going to be a matter of when, not if, it'll be acceptable in all future PHP projects.


Note 1: But not identical, given null-coalescing operators only test on non-null values (and not truthy values like PHP), and the ?: syntax doesn't suppress undefined notices as you mentioned in the comments.