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

  1. The ternary operator is not perfect for every situation, small php files with simple if/else statements suit the ternary operator best.
  2. Some argue it decreases readability, they're probably correct but it's a matter of preference and what works for you.
  3. 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!

ABOUT THIS AUTHOR

Hi, I'm Drew Douglass and I make sure Dev-Tips.com runs smoothly. I also work for Envato Support and write for NETTUTS.com and ThemeForest.net. I'm passionate about anything web development related, especially php, WordPress, MySQL, and jQuery. Feel free to follow me on twitter.
  1. Paul
    January 28, 2009 at 6:34 pm
    • January 28, 2009 at 7:02 pm

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Popular Series

Output Buffering Articles
Build a Custom AJAX and PHP Contact Form
The Ultimate Image Gallery Manager.
ThemeForest Premium Site and WordPress Templates