PHP Shorthand Conditional Statement


2 minute read

Listen to article
Audio generated by DropInBlog's Blog Voice AI™ may have slight pronunciation nuances. Learn more

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

<?=$age=='old'?'Hi Old Guy':'Hi Youngster';?>

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

<a href="about.php" <?=$page=='about'?'class="now"':'';?>>About Us</a>

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';.

« Back to Blog