The Ternary Operator
The ternary
operator is so named because it is the only operator that takes three operands: a condition, a result for true
, and a result for false
. If that sounds like an if
statement to you, you are right on the moneyâthe ternary operator is a shorthand (albeit very hard to read) way of doing if
statements. Here's an example:
$agestr = ($age < 16) ? 'child' : 'adult';
First there is a condition ($age < 16
), then there is a question mark, and then a true
result, a colon, and a false
result. If $age
is less than 16, $agestr
will be set to 'child
'; otherwise, it will be set to 'adult
'. That one-liner ternary statement can be expressed in a normal if
statement like this:
if ($age < 16) { $agestr = 'child'; } else { $agestr = 'adult'; }
So, in essence, using the ternary operator allows you to compact five lines of code into one, at the expense of some readability.
You can nest ternary operators by adding further conditions into either the true or the false operands. For example:
$population = 400000; $city_size = $population < 30 ? "hamlet" : ($population < 1000 ? "village" : ($population < 10000 ? "town" : "city")) ; print $city_size;
In that example, PHP first checks whether $population
is less than 30. If it is, then $city_size is set to hamlet
; if not, then PHP checks whether $population
is less than 1000. Note that an extra parenthesis is placed before the second check, so that PHP correctly groups the remainder of the statement as part of the "$population
is ...
Get PHP in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.