Sep 3, 2013 | php

Even shorter ternary operators in PHP using ?:

!
Warning: This post is over a year old. I don't always update old posts with new information, so some of this information may be out of date.

Today I discovered something about PHP's ternary operator that gave my DRY soul a little bit of joy.

The PHP ternary operator is often a key player in the terseness vs. clarity argument. A brief refresher: The PHP ternary operator allows you to write single-line comparisons, replacing code like the following:

<?php
if (isset($value)) {
    $output = $value;
} else {
    $output = 'No value set.';
}

with this:

<?php
$output = isset($value) ? $value : 'No value set.';

The second code example is clearly simpler, and in many cases (although certainly not all), it still retains enough clarity to be a worthy tool. There's plenty of debate about whether the ternary operator sacrifices clarity at the expense of conciseness; let's just say it's a tool, and like any tool, it can be used well or poorly.

The syntax for the regular ternary operator is (expression) ? value if truthy : value if falsy. The expression can also just be a single variable, which will test whether the variable is truthy or falsy:

<?php
$output = $value ? $value : 'No value set.';

The problem is, the above example is both common and annoyingly repetitive: Having to write $value twice like that just feels wrong.

Well, I discovered today that PHP 5.3 introduced an even terser syntax for this use of the ternary operator. You can learn more at the docs, but here's how we could make the above example even more concise:

<?php
$output = $value ?: 'No value set.';

If this looks familiar, it's because it is: this is exactly how PHP shortens other operators, like shortening this:

<?php
$value = $value . $other_value;

to this:

<?php
$value .= $other_value;

For the sake of clarity, just because we can shorten something doesn't mean we should. But, when we can write terse code that is also appopriately clear, we should, and this feature allows us to DRY up the ternary operator in many cases.


Comments? I'm @stauffermatt on Twitter


Tags: php

Subscribe

For quick links to fresh content, and for more thoughts that don't make it to the blog.