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.

[code lang=”php”]$lang = $_POST[‘boj_adminlang_lang’] == ‘es_ES’ ? ‘es_ES’ : ”;[/code]

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:

[code lang=”php”]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!

3 responses to “The PHP ternary operator”

  1. Andy Roberts Avatar

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

    1. keithdevon Avatar

      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 Avatar

    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

Your email address will not be published.