The PHP ternary operator

In my quest to master PHP, I’m going to start investigating some of the bits I’m unfamiliar with, and blogging about them.

This morning, I was reading through the excellent “Professional WordPress Plugin Development” by Brad Williams, Ozh Richards and Justin Tadlock (I’ve made a resolution to read a bit every couple of days). In the user settings section there is an example of a ternary operator.

$lang = $_POST['boj_adminlang_lang'] == 'es_ES' ? 'es_ES' : '';

Frankly, I’m embarrassed that I’ve come across this syntax so many times without taking the time to understand it. Especially because it is so simple.

The above code is short for:

if( $_POST['boj_adminlang_lang'] == 'es_ES' ) {
$lang = 'es_ES' ;
} else {
$lang = '' ;

I’ve written so many statements using the longhand version. Time to level up!


WordPress SEO: 10 tips for better search rankings

FREE E-book. Learn the basics of WordPress SEO and how to improve the key metrics
  • We won't sell your address to anyone. We hate spam too.
View my portfolio Get in touch

3 Responses to “The PHP ternary operator”

  1. Andy Roberts

    The longhand version is much better though isn’t it. Why would you want to write code that doesn’t make the logic explicit?

    • keithdevon

      Good point Andy. I guess the main reason for posting this was to cement my understanding of the syntax, as a lot of developers use it. Whether I do or not remains to be seen!

  2. Rob George

    I don’t think the below works for your example but if you’re just evaluating a value as true/false then since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise..

    I think the longhand is more readable but it’s good to know the different shorthand notations.


Leave a Reply