Using the PHP Ternary Operator

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

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • http://josephscott.org/ Joseph Scott

    There is another way to tighten up your original example, and still maintain a high degree of readability:

    $message = “Sorry, you aren’t that cool!”;
    if ( $coolFactor >= 10 ) {
    $message = “You are one cool dude!”;
    }

    The ternary operator has some uses, but is also easily abused.

    • Pascal

      @Joseph Scott, maybe it’s still readable, but make no sense to me. If you see “if else”, you know from the beginning that only one of the instructions will execute. Your example generates two assignments, if condition is true. Maybe in this example it’s OK, but what if you have to load data from file or execute SQL statement :)

    • Joe

      What you are leading toward is the concept of priority among many outputs, not a simple boolean decision.
      For example, suppose a University hasmany Professors hasmany Classes. Each of these resources might have an EmailTemplate, so when a University sends an email, it uses its template. If a Professor sends an email but does not have a template, it bubbles up to the University’s template.

      $template = new DefaultTemplate;
      if ($prof->uni->template) $template = $prof->uni->template;
      if ($prof->template) $template = $prof->template;

    • http://activedeveloper.info mhitza

      Depends on what you think abused means. Take this example which I think it is well in the accepted area:

      return is_null($this->resource) ?
      false :
      false === $candidate->isCvHidden() && (
      $candidate->hasAppliedTo($this->company) ||
      $this->company->hasAlreadyDownloadedCvOf($candidate) ||
      $this->resource->getCVDownloadsRemaining() > 0
      );

      • James

        @mhitza umm… yeah. I’d call that abuse.

    • http://www.maltblue.com/ Matthew Setter

      I like the article Arman – nice work. I agree with your point about not abusing it. As the ternary operator is such a terse construct, it’s easy to use it in such a way that it’s nearly illegible – leading to sneaky logic bugs – as was clearly examplified by @mhitza.

      Joseph Scott’s example was a nice alternative or complementary approach to the ternary operator which I use quite a bit. In that case, a default value is assigned and only overridden if necessary – which obviates the need for the else clause.

      Great stuff.

  • http://fawadafr.com Fawad Rashidi

    Thanks Amanda. I agree with your post. I don’t mind working with ternry as long as it one line and easy to follow. I have seen really complex ones that some developers abuse it and it becomes extremely hard to debug and read the code.

  • http://www.eastdevonit.co.uk Dan – Web Designer

    Great stuff, thanks
    I was looking at some code written like this just a few days ago and was somewhat confused!!
    Now I know what the hell it meant!!!
    How do you pronounce ternary anyway…

  • http://gumz-ex-press.com Gumz

    Thanks for this guidelines. I got lost before when I first encountered the ternary operation without middle expression.

  • DeanyWebGeek

    Great article, enjoyed it emmensely :-)

  • Jonas

    Worth noting is that $favoriteColor = $_GET["color"] ?: “pink”; will produce a Notice for all times that “color” isn’t set via query string.

  • Jon

    Enjoyed the article.