PrimitiveType

PHP's Ternary Operator

PHP's ternary operator is an operator that works on 3 expressions. It first tests a boolean expression for truth and returns the second expression if true, or the third expression if false. The ternary operator can often be used to replace a simple if-else statement, reducing the number of lines of code in a script or program. Though novices sometimes find it difficult to understand, the ternary operator quickly becomes a useful tool in a programmer's toolbelt because of its expressive power.

The ternary operator takes the following form:

conditionToTest ? returnIfTrue : returnIfFalse

Whilst the first expression must be a boolean (or at least will be evaluated as such if it is not), the last two can be of any type. Strictly speaking, you can omit the middle expression as of PHP 5.3, in which case if conditionToTest evaluates to true, it will be returned, or the last expression otherwise, but I would avoid doing so as it is not something widely practiced. Also, whilst you can nest or stack ternary expressions, it is advised against in PHP because of unexpected results.

To give an example of the usefulness of the ternary operator, consider this if-else statement:

if ($age >= 18) { print 'Welcome blah blah blah...'; } else { print 'You need to be at least 18 to qualify...'; }

This can be replaced with:

print $age >= 18 ? 'Welcome blah blah blah...' : 'You need to be at least 18 to qualify...';

Sometimes it is helpful to use parentheses around a ternary expression to clarify exactly what is going on. Consider this example in which parentheses help to show which part of a string concatenation statement depends on a condition:

$msg = '<span style="color:#' . ($isError ? 'FF0000' : '00FF00') . '">' . $someText . '</span>';

In the code above, if $isError is true, the message will be red, otherwise it will be green.

In a long program, saving on lines of code can be a welcome thing. Of course, you don't want to make your code hard to understand, but most developers should learn how to use the ternary operator and as such you can consider it safe enough to use. Other programming languages also have the ternary operator, for example, Java, C and C++, so it is not something that is unique to PHP in the slightest, and should be familiar to many programmers.