PHP Quick Tip: Using the Ternary Operator
Tuesday, January 13th, 2009
A reader wrote in yesterday providing a piece of php code asking what a specific part of it was doing. Turns out, the code was using what is known as the ternary operator. Today, we will quickly go over what the ternary operator is and how to use it in your php applications.
What does it look like?
$yourVar = ( $varB == 'dev-tips' ) ? 'I am on Dev-Tips' : 'I am not on Dev-Tips';
What does it do?
Using the ternary operator is like shorthand for saying 'if this condtion is true, then do this, if not then do this'. In the code above, we are saying if $varB is equal to 'dev-tips' then $yourVar will equal 'I am on dev-tips'. If not then it will equal 'I am not on dev-tips'. That's all there is to it!
Notes and Pitfalls
- The ternary operator is not perfect for every situation, small php files with simple if/else statements suit the ternary operator best.
- Some argue it decreases readability, they're probably correct but it's a matter of preference and what works for you.
- From the manual:"It is recommended that you avoid "stacking" ternary expressions."
If you enjoyed this article, you might consider subscribing to our rss feed to stay updated with all the latest tips and articles!
Article Sponsored by:
Do you like teh codez? So do we, and that's why you should add us to your watchlist on Snipplr. You'll get to keep up with all of the latest code snippets and scripts that we post.









My favorite trick here is using the ternary operator as a fake “gated or”. By that, I mean, the value returned is the second value only if the first is falsy.
$val = ($x = $a) ? $x : $b;
If A is truthy, then $val === $a.
If A is falsy, then $val === $b.
This is handy when getting the results of a function.
$val = ($x = myFunction()) ? $x : anotherFunction();
I could see how that could be very handy, some would probably complain about the readability, but I think its a nice little technique if it works for you
Much thanks for your comment and input Paul.