I mentioned a few days ago that I finally got to use ternary operations in my code and I was excited.

I have a tendency to write my code out long form, which stems from how I actually sit down and think about my code. For example, when I need to check if specific parameters are set, I write it out like this:

If variable X is equal to FOO, then do BLAH. Else do DEFAULT!

When I translate that to PHP code, it becomes this:

if ( $variable == 'FOO' ) {
    BLAH;
} else {
    DEFAULT;
}

There’s nothing particularly wrong with it, but it can get a little long. And then consider code like this:

if($_POST['variable'] == 'no' || $_POST['variable'] == 'yes'){              
    $variable = $_POST['variable'] ;
}

That has two issues. The first is that I’m trusting my data a little more than I should and not sanitizing when I save the variable. The second is I’m not validating smartly. If I want to be smarter, I do this:

if( $_POST['variable'] == 'yes'){              
    $variable = 'yes ;
} else {
    $variable = 'no';
}

At this point, I’m no longer allowing my code to be anything but yes or no, and if someone puts in ‘maybe’ as a value for the POST data, that’s nice but I’m forcing no.

Another alternate way is this:

$variable = 'no';
if( $_POST['variable'] == 'yes'){              
    $variable = 'yes ;
}

There I default to ‘no’ and only pick ‘yes’ if it’s set to yes. This code is somewhat better because it only has one check and it’s obvious what my default is.

But we can be even smarter! The trick is that I have to rethink how I’m checking for things. If all I care about is if a comparison is true or false, and I want to save a specific value to a variable based on that, then I can do my code all in one line:

$variable = ( $_POST['variable'] == 'yes' )? 'yes' : 'no';

This is the magic of the ternary operators. With it I get one line that checks for a specific result and defaults when that’s not it. You can make it more complicated, as long as the result is true/false. Like here:

$schema = ( is_ssl() || get_setting( 'plugin-force-ssl' ) )? 'https' : 'http';

Obviously they won’t work in all situations, and there are some cases where the two possibilities are going to make the code harder to read, but they can be downright nifty if you do them right.

Reader Interactions

%d bloggers like this: