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.

 

Next chapter: The scope resolution operator >>

Previous chapter: Complete operator list

Jump to:

 

Home: Table of Contents

Follow us on Identi.ca or Twitter

Username:   Password:
Create Account | About TuxRadar