PHP Shorthand Conditional Statement

Here’s another quick hit from my php snippets. You can see a review of a lot of ways to do this on David Walsh’s post on the subject. However, I wanted to write it as short as possible to be used within pages. I use this a lot to add css classes into tags.

The if/else shorthand php snippet

{code type=php}
<?=$age==’old’?’Hi Old Guy’:’Hi Youngster’;?>
{/code}

The breakdown of the statement in a diagram

php shorthand diagram

In this example we say “if the $age is old” then echo “Hi Old Guy” else echo “Hi Youngster”. The syntax highlighting is not perfect since I’m using the shorthand open and closing php tags. But this is the absolute shortest you can make this statement. You’ll also notice I’m using single quotes. This is handy because then you do not need to escape double quotes like in the example below that I use a lot for adding a class to a tag.

Adding a class to a tag with a php shorthand statement

{code type=php}
<a href=”about.php” <?=$page==’about’?’class=”now”‘:”;?>>About Us</a>
{/code}

In this example I have a simple anchor tag for my “About Us” menu item. Then I’ve put in the conditional statement indicating if the $page variable is equal to “about” then echo class="now". Then of course you will have some additional styling put onto your .now class to indicate the current page. Then in the top of your about.php file you just have to set the $page variable to $page='about';.

Did you enjoy the post? Why not or subscribe to my RSS feed?

3 Replies to “PHP Shorthand Conditional Statement” Reply Now »

Sep 28 2013

Dave Macaulay says:

12:02 pm

You should really avoid using short tags and instead use <?php echo ‘string’; ?>.

Read more about it here:
http://stackoverflow.com/questions/200640/are-php-short-tags-acceptable-to-use 

Sep 28 2013

Jesse Schoberg says:

11:28 pm

I don’t know Dave… I’m having trouble finding a compelling argument there. I have heard people mention this in the past, and I am no expert. It just seems for many smaller sites it’s a lot cleaner.

Sep 29 2013

Dave Macaulay says:

3:27 am

It’s an interesting argument. If you’re writing code to support older versions the short hand version may break. I wrote a system many years ago entirely using short codes, one customer didn’t have it enabled so I had to go through and update the whole script.

You should never worry about how ‘clean’ your code looks against how it functions. It’s always better to write more code, that another human can understand easier, obviously with this they’re both easy to understand but the extra few characters using <?php could potentially save some headaches down the line. 

Leave Your Response

If you want your own icon get a gravatar.

About Schoberg

Jesse Schoberg

Jesse Schoberg is a web developer. He founded LJ Host in 2001. He has a passion for CSS and other web technologies.

More About Schoberg