There is a special if/else functionality available that not many programmers know how to utilize that I now want to share with you. This function is called a Ternary operation. The ternary operation takes 3 arguments, The first which is the conditional expression, the second is what get returned if the conditional expression is true, the third if it returns false.

First let’s see a standard if/else, this example should look familiar.

if($age > 50) {
    echo 'You are old!';
} else {
    echo 'You are young!';

Now let’s try that with the shorthand version of if/else

echo ($age > 50 ? 'You are old!' : 'You are young!');


What was that you say? That is about what I said the first time I encountered this type of conditional statement. If you look closer at this example you can see the same conditional expression from the first example followed by a question mark. Then we have 2 strings divided by a colon. The first of the 2 strings is returned if the condition is true, and the second is returned if the condition is false.

If you are new to programming this kind of operations may be hard to follow,  at least to remember when writing your own code. But as soon as you get used to it, you will end up with much cleaner code provided that you don’t pull any crazy stunts using this method.

What about elseif?

Yes it’s possible to do elseif statements using this method as well if your’e willing to sacrifice some of the readability. To do elseif you need to wrap a ternary operation as the false part of you main if/else statement.

echo ($age > 50 ? 'You are old!' : ($age < 20 ? 'You are too young!' : 'You are young!'));

And if you really want to get down and dirty you could replace the true part with another shorthand version although this is not something I would recommend doing.

echo ($age > 50 ? ($age > 75 'You are too old!' : 'You are old!') : ($age < 20 ? 'You are too young!' : 'You are young!'));