Skip Navigation

Ternary Conditionals

Ternary conditionals (using the "ternary operator", sometimes known as the "trinary operator") are a part of PHP that many simply steer clear of, despite their usefulness. They can save a great deal of time when writing code and can make for much easier code to read and edit later on. They look strange to many people though, which might explain why they are not as widely used as they could be.

Consider a normal conditional statement, like the following. It begins by evaluating a condition. If that condition is true, it follows one path. Sometimes, an alternate path is specified if the condition is not true (the 'else' section). Sometimes, you can have a list of several possible conditions in a row (using 'if ... elseif ... else' or 'switch ... case').

  1. if (condition) {
  2. variable = value-if-true;
  3. } else {
  4. variable = value-if-false;
  5. }

However, a simple situation like the above is a perfect candidate to convert to a ternary conditional. You have one condition, and if it is true, the variable is given a certain value - if false, a different value. A ternary conditional can accomplish the same thing, concatenating it into one simple line of code.

  1. variable = (condition) ? value-if-true : value-if-false;

Ternary conditionals take the above form. You do not necessarily need to have a "variable = " section (as you will see later on), but usually that is what this is used for. The above does exactly the same thing as the 'if ... else' statement earlier. If the condition evaluates to true, the variable will be assigned the value in the "value-if-true" section, otherwise it will receive the "value-if-false" value.

In practice, you could use the ternary conditional to, for example, greet a user depending on whether it is currently morning or afternoon. Using traditional code ('if ... else'), you might write something like this:

  1. if (date("G") < 12) {
  2. echo 'Good morning';
  3. } else {
  4. echo 'Good afternoon';
  5. }

The same statement, using a ternary conditional, would look like this:

  1. echo (date("G") < 12) ? 'Good morning' : 'Good afternoon';

Note that in this example, we've used "echo", rather than assigning a value to a variable. The above is exactly the same as this, which does make use of a variable:

  1. $greeting = (date("G") < 12) ? 'Good morning' : 'Good afternoon';
  2. echo $greeting;

Another situation in which I often use ternary conditionals is when displaying rows of data. It can often be much easier for a user to see what is going in if the rows alternate background colour, and the following code can be useful for that:

  1. $i = 1;
  2. echo '<table>';
  3. while ($data = mysql_fetch_array($result)) {
  4. echo ' <tr>';
  5. echo ' <td bgcolor="';
  6. echo (($i % 2) == 0) ? '#eee' : '#ddd' ;
  7. echo '">';
  8. echo $data['field'];
  9. echo ' </td>';
  10. echo ' </tr>';
  11. $i++;
  12. }
  13. echo '</table>';

The above code will cycle through a result set, displaying each item in a new row. The background colour of the row will alternate between shades of grey, controlled by the ternary conditional on the bold line.

Ternary conditionals make for tidier code. Use them - if not for yourself, then for whoever is going to end up editing your scripts!

16 comments

kensplace
United Kingdom #1: June 24, 2004
Also known as IIF in some basic's, and little known that the sinclair spectrum supported it! you could do a similar thing in for example a print statement or whatever to print your desired result, depending on the outcome of a condition. Good old clive ;) (ok, he didnt program it, but he knew someone good)


Nice article, brought back memories

jh
United States #2: October 30, 2004
This article was VERY useful. Ternary conditionals have baffled me for long enough, now I can look back and LAUGH!!!!!!! HA! HA! HA!
 United States #3: May 20, 2005
I think the following link is broken.

http://www.ilovejackdaniels.com/php/ternary-conditionals/
Frank
Unknown #4: May 22, 2006
Excellent article - very helpful.
Thanks!
Tony
Netherlands #5: July 25, 2006
I use it a lot when quickly mixing code and html because then an if / else constructrion with all the <?php and ?> and { } etc... realy makes it unreadable.
Like this:

Price: <?=($price==0 ? "Call us!" : $price);?>
Is it wrong to admit to just having used the ternary syntax for the first time in PHP?

Anyway, thanks for the article.
This site continues to amaze me!
TD
United Kingdom #8: December 17, 2006
In your row example, would it not be better to use CSS and put it in the <tr> tag not every <td> tag?

echo ' <tr class=($i % 2) == 0) ? 'something' : 'else' >';
echo ' <td>;
...

Or would this not work? Haven't actually tried it.. not got the time ;)
TD: Yes, that would be better. My personal preference would be to "stripe" the rows via JavaScript, since 'even' and 'odd' classes have little to no semantic purpose and shouldn't be in your HTML.
AKX
Finland #10: May 11, 2007
Not to mention you can squeeze a bit more speed out of that zebra striping code with this:

echo '<tr class="'.($i&1?'this':'that').'">';

Modulo is slower than bitwise AND, and in this case, it's the very same thing. :)
There is no reason to use ternary notation. If anything it is harder not easier to read and cannot be extended to include more options other than true or false. Succinct code may be great for the hard-core programmer but for the developer who must modify crap it is a nightmare. If speed is so important than compile the final product when everything is completed.
Paul
United Kingdom #12: July 13, 2007
AKX, does bitwise AND (&) return true if both bit values added give an even result, and false if an odd result? I can see how it would be quicker.

"If speed is so important than compile the final product when everything is completed."

With PHP being an interpretive language that would be challenging!
Meat_PoPsiclez
Canada #13: July 23, 2007
In response to "Paul, United Kingdom", you can actually run half baked php applications utilizing zend optimizer. With large scripts where not all of the code is run, compilation time can sometimes exceed actual processing time, and zend can make substantial gains.

However, it really doesn't apply here, because the actual code is, from what I can gather, generated in exactly the same way, and doesn't run any faster.
Thanks for the explanation. I have used this a lot and love it, but I forgot the syntax and couldnt remember what it was called. It does save time and I use it on the alternating rows of a table all the time.
Me and Ternary can now be best friends!
makes me think of the Oracle Docode statement.

select id, decode(status,'A','Accepted','D','Denied','Other')
from contracts;

Post Your Comment

· Comments with keywords instead of a name have their URLs removed.
· Your email address will not be displayed or shared.

Live Comment Preview

 United States #17: 1 minute ago