The Ternary Operator: Usage and Examples

This article is meant for users of PHP, however, it may be a good resource for other programming languages as well.

What is the Ternary Operator?

The ternary operator is an operator that takes three arguments. The first argument is a comparison argument, the second is the result upon a true comparison, and the third is the result upon a false comparison. If it helps you can think of the operator as shortened way of writing an if-else statement. It is often used as a way to assign variables based on the result of an comparison. When used correctly it can help increase the readability and reduce the amount of lines in your code.

How Do I Use the Ternary Operator?

The ternary operator is really very simple to use. The ternary operator, as mentioned above, consists of three parts, the condition, the result if true, and the result if false.

//ternary operator - example 1
   $variable = ($x==1) ? true: false;

Let’s say that we apply a higher shipping charge of $15.00 to orders placed in the east. If our order is not placed in the east then the shipping charge is $10.00. The following examples show the if-else statement and the ternary statement.

//if-else
   if($zone=='East')
   {
      $shipping_charge=15.00;
   }
   else
   {
      $shipping_charge=10.00;
   }

//ternary operator
   $shipping_charge = ($zone=='East') ? 15.00 : 10.00;

As you can see, what before was 8 lines of code has been reduced to one line. You can potentially reduce the if-else statement down to 2 lines of code and maintain readability, however to reduce it down to 1 line would make your code a lot less readable (and be bad programming practice in my opinion).

The ternary operator can also be nested so that different conditions can be tested based on a result of true. This is where you can get into trouble formatting and lose readability. We dig into the proper formatting later on.

//nested ternary operator
$variable = ($x==1) ? (($y==2) ? true : false) : false;

//equivalent if-else
if($x==1)
{
   if($y==2)
   {
      $variable = true;
   }
   else
   {
      $variable = false;
   }
}
else
{
   $variable = false;
}

When Do I Use the Ternary Operator?

Use the ternary operator to simplify your if-else statements that are used to assign values to variables. The ternary operator is commonly used when assigning post data or validating forms. For example if we were programming a comment form and wanted to ensure that the user entered their email address then we could write something like the following.

//is email address specified? Notify customer if not
$email_address = (isset($_POST['email'])) ? $_POST['email'] :
                      die('Please enter your email address');

As you can see, the ternary operator can be written on multiple lines. It may be more likely that the email field is empty rather than not set. So instead of checking if the email field is set the following example checks if it is empty.

//is email address specified? Notify customer if not
$email_address = (empty($_POST['email'])) ? die('Please enter your email address'): $_POST['email'];

I would use the ternary operator anywhere that I needed to assign a variable that changed based on the results of the comparison. However, the choice is up to you and what you are comfortable with.

Why Should I Use the Ternary Operator?

The ternary operator greatly increases the conciseness of your code. When it is formatted correctly it can also be very easy to read and, dare I say it, even easier then if-else statements.

There seems to be some controversy over when to use the Ternary Operator and when to use If-Else statements. Some will say that the Ternary Operator should only be used for simple variable assignments, like shown in example 1. Some say that if the ternary operator get’s to complex (nested) then it is far better to use an if else statement. I beg to differ – with good formatting, the ternary operator beats the if-else statement every time.

Take the following examples (inspired by this post on stackoverflow). The first example shows the traditional if-else statement and takes up 16 lines of code. The second shows a poorly formatted nested ternary statement that takes up 8 lines of code (cuts lines in half). The third example shows a properly formatted nested ternary statement that takes up 5 lines of code including an explanatory comment.

If-Else
//is this a leap year? - If-else
if(($year % 400) == 0)
{
   $isLeapYear=1;
}
elseif(($year % 100) == 0)
{
   $isLeapYear=0;
}
elseif(($year % 4) == 0)
{
   $isLeapYear=1;
}
else
{
   $isLeapYear=0;
} //if
Ternary Operator – Poorly Formatted
//is this year a leap year? - Ternary (bad formatting)
$isLeapYear =
   (($year % 400) == 0)
   ? 1
   : ((($year % 100) == 0)
      ? 0
      : ((($year % 4) == 0)
         ? 1
         : 0));
Ternary Operator – Properly Formatted
//is this year a leap year?
//--------------test expression-----result
$isLeapYear = (($year % 400) == 0) ? 1 :
              ((($year % 100) == 0)? 0 :
              ((($year % 4) == 0)  ? 1 :
                                     0));//default result

Though the if-else statement is more common and familiar, in my opinion, the ternary operator produces a far more readable and concise result.