Keith Devon

Menu

Tag: PHP

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!