Using the Ternary Operator in PHP

October 29, 2008

The ternary–also called the trinary–operator is a little gem in PHP (and other programming languages) which you might run across. Its syntax is unusual at first, but it allows you to simplify more complex conditionals into one line statements.

The basic syntax of the ternary operator is:

(condition) ? 'true' : 'false';

In other words, PHP will evaluate the condition. If the condition is true, the first value–after the question mark–is returned. If the condition is false, the second value–after the colon–is returned.

The key to using this operator is understanding that a value is returned by the expression. This value must be handled, as you would handle something being returned by a function. Just two sample uses of this would be:

  • Assign a value to a variable.
  • <?php
    $sort = (isset ($_GET['sort'])) ? $_GET['sort'] : 'asc';
    ?>
    
  • Print a message.
  • <?php
    echo 'You entered your name as ';
    echo (empty ($_POST['name'])) ? '<b>you failed to enter your name!</b>' : $_POST['name'];
    ?>
    

In the first example, the $sort variable will be assigned the value of $_GET[‘sort’], if the $_GET[‘sort’] variable is set. Otherwise, the $sort variable will be assigned the value of asc.
In the second example, the script will either print “You entered your name as <b>you failed to enter your name!</b>”, if no $_POST[‘name’] value is present, or it will print “You entered your name as XXXX” (where XXXX is the value of $_POST[‘name’]), if $_POST[‘name’] is not empty.

You could rewrite these two statements like so:

<?php
if (isset ($_GET['sort'])) {
	$sort = $_GET['sort'];
} else {
	$sort = 'asc';
}
?>

<?php
echo 'You entered your name as ';
if (empty ($_POST['name'])) {
	echo '<b>you failed to enter your name!</b>';
} else {
	echo $_POST['name'];
}
?>

A final example is this one, which I used in my PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide book:

<?php
// ... lots of code above.

// Fetch and print all the records.
$bg = '#eeeeee'; // Set the background color.
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
	$bg = ($bg=='#eeeeee' ? '#ffffff' : '#eeeeee'); // Switch the background color.
	echo '', stripslashes($row[0]), '', $row[1], '';
}

// ... lots of code below.
?>

In that example (from Script 12.15, view_users.php), a default background color is set. For each iteration of the while loop, the script will assign $bg a value based upon its existing value. If its existing value is equal to #eeeeee, then its value is switched over to be #ffffff. Conversely, if its existing value is NOT equal to #eeeeee (the condition is false), then its value is assigned to be #eeeeee. This results in alternating row colors.