The Ternary Operator

There are three operators that are complicated enough to get their own section, of which the first is the ternary operator. It is called the ternary operator because it 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:

<?php
    $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:

<?php
    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.

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: The scope resolution operator >>

Previous chapter: Complete operator list

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.