How to Use the PHP Ternary Operator

By Jonathan   |   November 11, 2007   |   Copyright 2007 - All Rights Reserved

The ternary operator is a shortcut comparison operator that replaces an if-else statement in a PHP script. If you use a lot of comparison statements in your scripts, this can greatly reduce the number of lines of code. The ternary operator is really very simple to use, but it does tend to confuse newbie PHP programmers.

The ternary operator is only used for assignment of values to variables and to reduce the lines of code and compact PHP statements. Although it is a little more difficult to read, once you understand how it operates, it is simple to use and understand.

There are four parts to a ternary statement. The first is the variable where the result of the conditional test will be assigned. The second part is he condition that is being evaluated for a True or False boolean result. The third part is the value that is assigned if the condition is true. The last part is the value assigned if the condition is false.

$variable = condition ? if true : if false

Let’s start with the most common use of this shortcut. If your scripts are processing large amounts of data that users have entered using HTML forms, you are undoubtedly assigning the form values to variables. When a value does not exist, a default value would normally be assigned like this:

 if (isset($_POST['statusID']))
  $statusID = $_POST['statusID'];
  $statusID = 1;

Using a ternary operator statement, that same conditional test and assignment of values would look like this:

$statusID =  (isset($_POST['statusID'])) ? $_POST['statusID'] : 1;

The interpretation is: If a value has been passed in the form variable named statusID via the POST method, assign that value to $statusID. If no value was passed, assign the default value of 1.

Sometimes you will see a variation of the same statement that looks like this:

$statusID = (empty($_POST['statusID'])) ? 1 : $_POST['statusID'];

The result will be the same, but the condition being tested has been flipped–rather than testing to see if a value does exist, it is testing to see if a value is missing. The interpretation is: If a no value has been passed via the POST method, assign the default value of 1. If a value was passed, assign that value to $statusID.

Ternary operators really shine when assigning text to simple messages, such as:

$msg = ($age < 21) ? 'Minor - no drinks' : 'Adult - have a beer';
echo $msg;

The interpretation is: If the value in $age is less than 21, then “Minor, no drinks” is assigned to $msg, else “Adult – have a beer” is assigned.

Here is a cool method for assigning alternating background colors to table rows or other tabular displays of data.

$names = array("John Doe","Susan Doe","Snuffy Smith","Jack Jones");
$c = count($names);

echo "<table width='300' style='border:1px solid #c7c7c7'>\n";

for($i=0; $i<$c; $i++)
 $bg = ($i % 2 == 0) ? '#d7d7d7' : '#ffffff'; 
 echo "<tr height='10' bgcolor='$bg'><td> $names[$i] </td></tr>\n"; 

echo "</table>\n"; 

Running this code will display the following:

ternary operator example

While this example uses an array, it is just as simple to do the same using data extracted from MySQL.

About Jonathan

Jonathan is a tech evangelist and WordPress website building guru, Over the years he has built hundreds of sites and currently specializes in building responsive design web sites.

5 Responses to How to Use the PHP Ternary Operator

  1. Adam says:

    I personally can’t wait for the introduction of PHP6′s optional adaptation of the ternary operator. Instead of doing like:

    $myVar = $_GET['myVar'] ? $_GET['myVar'] : ‘Not set’;

    You will be able to do:

    $myVar = $_GET['myVar'] ?: ‘Not set’;

    How handy will that be!

  2. Doogie says:

    There are a lot of nice features in PHP 5 and the upcoming PHP 6. Unfortunately, most hosting companies have still not upgraded from PHP 4. :(

  3. Joyel says:

    They may not currently be migrating but a lot of them are going from 4 to 5. If the PHP community would get in contact with there hosts and start talking to them about upgrading they will (create demand and they will respond).

  4. Inzei says:

    @Adam: IIRC that’ll still result in E_NOTICE when trying to get a value with nonexistent key, and thus such markup should be avoided.

  5. Pingback: PHP Ternary Operator | KC-TUTOR