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').
if (condition) {
variable = value-if-true;
} else {
variable = value-if-false;
}
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.
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:
if (date("G") < 12) {
echo 'Good morning';
} else {
echo 'Good afternoon';
}
The same statement, using a ternary conditional, would look like this:
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:
$greeting = (date("G") < 12) ? 'Good morning' : 'Good afternoon';
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:
$i = 1;
echo '<table>';
while ($data = mysql_fetch_array($result)) {
echo ' <tr>';
echo ' <td bgcolor="';
echo (($i % 2) == 0) ? '#eee' : '#ddd' ;
echo '">';
echo $data['field'];
echo ' </td>';
echo ' </tr>';
$i++;
}
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!









27 Comments
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
#1, kensplace, United Kingdom, 24 June 2004. Reply to this.
This article was VERY useful. Ternary conditionals have baffled me for long enough, now I can look back and LAUGH!!!!!!! HA! HA! HA!
#2, jh, United States, 30 October 2004. Reply to this.
I think the following link is broken.
http://www.addedbytes.com/php/ternary-conditionals/
#3, testing, United States, 20 May 2005. Reply to this.
Excellent article - very helpful.
Thanks!
#4, Frank, Unknown, 22 May 2006. Reply to this.
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);?>
#5, Tony, Netherlands, 25 July 2006. Reply to this.
Is it wrong to admit to just having used the ternary syntax for the first time in PHP?
Anyway, thanks for the article.
#6, Rob Lewis, United Kingdom, 28 September 2006. Reply to this.
This site continues to amaze me!
#7, Richard Duncan, United Kingdom, 7 December 2006. Reply to this.
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 ;)
#8, TD, United Kingdom, 17 December 2006. Reply to this.
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.
#9, John Zeratsky, United States, 30 January 2007. Reply to this.
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. :)
#10, AKX, Finland, 11 May 2007. Reply to this.
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.
#11, Sloth, Sweden, 9 July 2007. Reply to this.
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!
#12, Paul, United Kingdom, 13 July 2007. Reply to this.
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.
#13, Meat_PoPsiclez, Canada, 23 July 2007. Reply to this.
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.
#14, Jason, United States, 13 February 2008. Reply to this.
Me and Ternary can now be best friends!
#15, Richie, United States, 17 April 2008. Reply to this.
makes me think of the Oracle Docode statement.
select id, decode(status,'A','Accepted','D','Denied','Other')
from contracts;
#16, Andreas, Switzerland, 26 September 2008. Reply to this.
These took me a while to figure out and i didn't know what they were until 5 mins ago :)
Well explained!
#17, POG1, United Kingdom, 11 January 2009. Reply to this.
@TD: Classes would be better, but I think for the sake of the example the bgcolor was used.
#18, Alex, Australia, 11 February 2009. Reply to this.
Well I'm five years late but what the hell :) Thanks a bunch, this has helped me out a lot.
~ Chris
#19, Chris, United Kingdom, 20 April 2009. Reply to this.
$my_state=(the article was very helpful) ? "Thank you very much!":"It was not helpful.";
print $my_state;
RESULT:
Thank you very much!
#20, David Toth, United Kingdom, 26 July 2009. Reply to this.
Great tutorial. This has made my code much MUCH easier to deal with.
#21, Matthew, United States, 12 October 2009. Reply to this.
Thanks for the post, using your fine example i just wrote my first ternary expression!
#22, pThomas, USA, 8 January 2010. Reply to this.
Clear and useful articles, I've really appreciated it. Thank you :)
Carlo
(And Happy New Year ;)
#23, Carlo Rizzante, Denmark, 8 January 2010. Reply to this.
Thanks for the great article. That is exactly what I needed for my web site: <a href="">Print and Design</a>
#24, LD, uk, 15 July 2010. Reply to this.
What happens with the following statement?
$x = ($test) ? foo($a) : bar($a) ;
where foo and bar are functions? Are both evaluated with just one result being used or is just one of the functions evaluated?
Paul
#25, Dr Paul A Daniels, UK, 25 August 2010. Reply to this.
@Paul, ony foo() is called if $test is true, only bar() is called if $test is false.
Peter
#26, Peter Walter, 11 October 2010. Reply to this.
Great read! I was wondering if anyone knew if using Ternary operators is more efficient during run-time?
#27, Jared, Canada, 17 November 2011. Reply to this.