Every good programmer should constantly be looking for ways to improve the look and readability of their code. One of my favorite ways to reduce vertical length while maintaining readability is to use the lesser-known ternary comparison operator.

The Ternary Operator is unique when it comes to PHP's available comparison options. Not in the sense that it does something that the other operators don't, but that the functionality it offers is not seen anywhere else.

Basic Ternary Syntax:

The syntax of the ternary operator is not hard to understand. If the comparison is TRUE, the value after the '?' is returned, false and the value after the ':' is returned.

Let's take a look at an every day if-else statement:

Pretty standard stuff. The ternary operator is perfect for these short statements that end up taking a lot of precious vertical real-estate and don't really get that much done.

Ternary operators will return a value based on a set of normal comparisons. So what does that mean? Let's look at an example:

As you may have guessed, the whole point of this operation is to assign some value to $myvar. Our comparison comes first (notice there is no 'if'), followed by the possible values. The value after '?' will be returned if the comparison results in TRUE, while the value after ':' is returned if FALSE.

Let's kick it up a notch and nest some comparisons:

Normally, this is as far as I will go when it comes to nesting. Anything beyond one nested comparison and I would rather use if-else statements because the horizontal space gets huge. A poorly formatted if-else statement that is nested twice will almost certainly be easier to read than a neatly formatted ternary statement that is also nested twice.

There are also those who chose to format their ternary statements vertically but I fail to see the point in doing so if all you're accomplishing is trading the if-else keywords for '?' and ':'.

I have also found ternary operators to be exceptionally useful when dealing with html templates where every bit of php code is neatly printed useing <?=..?> formatting. Something like the following retains the neatness of being on one line while accomplishing the same effect of an if-statement.

Not the best example in the world but you get the idea.

Ternary Operator via PHP Manual

Get my RSS Feed!

Comments

Dave Doyle on (6.26.26 10:40 am) says

I love the ternary operator, but you're quite right, it can be abused.

In the Perl world a book by the name of "Perl Best Practices" uses the ternary extensively by lining up the code in a kind of table.  I'm not sure if this will work look right in here (if not, the = and : should be in a column along with all ? in a column) but how you layout the you can layout conditions and values in a chain like this:

$var = condition1 ? value1
     : condition2 ? value2
     : condition3 ? value3
     :              defaultvalue
     ;

I've found this very handy as opposed to a whole bunch of if/elsif/else statements.

 

Dave Doyle on (6.26.26 10:45 am) says

Well bugger.  That didn't work.  Anyhow, if this page didn't strip out the white space you'd find that lined up all neatly in a table.

 

Mike on (6.26.26 10:51 am) says

Sorry Dan,

I'm still trying to work out all the kinks with the comments. I'll try to clean it up a bit.

 

Aaron Oliver on (6.26.26 7:23 pm) says

Great examples, Mike, but I've got to disagree. I think the ternery operator makes code LESS readable, not more.

I've found that the brevity of the ternery operator is almost always overwhelmed by the mental gymnastics required to stop and remember how it works.

It's not common enough to be embedded in our brains the way if/else is, and it's kinda hard to read.

 

adam j. sontag on (6.26.26 10:23 pm) says

I've never had "problems remembering how it works," it's just one of those things you learn to recognise.

Anyhow...if you had multiple if else (more than 3) - isn't switch/case the operative move - both logically and from a readability standpoint.

 

Greg Patmore on (7.1.01 7:57 am) says

I dont know if I could live without the ternary operator!  I've heard all the gripes about readability and whatnot, but I think that if formatted correctly, it actually lends itself to higher readability then a long scroll of if/else conditions. This is especially true if the conditions are the determinant for assignment. I like Dave's way above, but I'd rather read code vertically then horizontally. What I think most PHP developers these days fail to utilize is the way PHP ignores whitespace when interpreting the code.

Here's how my team and I write them (slightly different then Dave's above):

$myVar = (condition1)
       ? trueVal1
       : (condition2)
       	   ? trueVal2
           : (condition3)
		? trueVal3
		: falseVal;

Just a noteworthy mention, I heard the new PHP6 will allow omission of the true side of the ternary statement allowing one to essentially write if(!condition) statements in a ternary way like this:

$myVar = (condition1)?:falseVal;

Not sure how this would be useful, or intuitive, but one should be aware I guess.

 
* Name
* Email (Will not be displayed)
Website