Shorthand If – The Ternary Operator

You are probably already familiar with shorthand if, also known as the ternary operator.

$value = get_value();
$default_value = 10;
$selected_value = ($value ? $value : $default_value);

If you haven’t seen shorthand if (line 3) before, it is a more elegant way to present simple if statements. The first expression (before the ?) is the condition. If this evaluates to true then the next expression (after the ?) will be returned. If the condition evaluates to false then the 3rd expression ($default_value in this case) will be returned.

If you have used the ternary operator before maybe you haven’t seen the even shorter version of its usage.

$selected_value = ($value ?: $default_value);

Note that the expression returned for true is now missing. This will automatically return the condition when it is true and the false expression when the condition is false. This is a great way to provide a default value, as in the example above, to cover cases where the variable you are working with might end up missing its value for an unexpected reason.

Leave a Reply

Your email address will not be published. Required fields are marked *