Using the PHP Ternary Operator

    Amanda Steigerwalt
    Share

    You’re probably already familiar with PHP’s if statement. It’s very similar to its counterparts in many other programming languages and represents one of the most fundamental concepts in programming. The if statement is easy to understand and easy to master. This is probably what you’re used to:

    <?php
    if ($coolFactor >= 10) {
        $message = "You are one cool dude!";
    }
    else {
        $message = "Sorry, you aren't that cool!";
    }

    But there’s a way to build on this concept and increase your $coolFactor a bit in the process. Allow me to introduce you to the ternary operator, which serves as a shorthand notation for if statements.

    Introducing the Ternary Operator

    Consisting of three parts, the ternary operator uses three expressions separated by a question mark and a colon. The question mark follows the test expression and can be thought of as asking, “Well, is it true?” The colon then separates your two possible values, the first of which will be chosen if the test expression is true, and the second if the test expression is false. Observe:

    <?php
    $message = ($coolFactor >= 10) ? "You're one cool dude!" : "Sorry, you aren't that cool!";

    One of my favorite uses for the ternary operator is to check whether or not a value is set and, if it isn’t, set the variable to a default value.

    <?php
    $favoriteColor = isset($_GET["color"]) ? $_GET["color"] : "pink";

    If a color parameter was passed in to the script from the URL, it’s value is assigned to $favoriteColor. If it wasn’t, the default value “pink” is assigned instead.

    Since PHP 5.3 it is possible to abbreviate ternary statements even more by excluding the middle expression. If the test expression evaluates true in a boolean context, its value is returned. Otherwise, the alternative is returned instead.

    <?php
    $favoriteColor = $_GET["color"] ?: "pink";

    But with great coolness comes great responsibility! Using the ternary operator properly can result in cleaner code; abusing the ternary operator can make things a mess. Never sacrifice readability or maintainability of your code to add a bit of flare.

    Don’t Abuse It!

    Before using the ternary operator, you should consider the complexity of the situation at hand. Avoid nesting or stacking your operations, even if you’re comfortable using them, as this can lead to very confusing code and unintuitive results. It’s still best to use if statements for complex situations. Above all else, be nice to the next guy and try to keep your code clean and easy to understand.

    It is also not unheard of to split ternary expressions into multiple lines. As with most things in programming, there are many variations on using whitespace liberally to improve the readability of your code.

    <?php
    $message = $isWinner
        ? "Congratulations! You just won a whole bunch of money and prizes!"
        : "Sorry, you didn't get any money or prizes this time.";

    As always, readability should be key.

    Summary

    The ternary operator may look a little weird at first but takes very little effort to master and is very easy to explain to others who may be maintaining your code in the future. With a little bit of practice you’ll be able to give your PHP code an extra dose of awesome and clear out a tiny bit of confusion from your life.

    Image via Arman Zender / Shutterstock