Set navigation menu inside WordPress Appearance > Menus

Web Developers Corner

Shorthand if/else for PHP

php

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!');

[adsense-banner]

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!'));

Tagged , , , ,

Share this post

PinIt

About Fredrik Hugås

Fredrik Hugås is a 28-year-old web designer from Norway, more comming ;)

View all posts by Fredrik Hugås →

One thought on “Shorthand if/else for PHP

  1. john

    This is the only tutorial what i could find with more statements in if else shorthands.
    Most are just toooo standard. Great i found this, thanks !

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>