Shorthand/Shortcode PHP If statements

Recently, I have spotted that I have been creating long if statements, and the amount of code needed for a simple "if this, then show that text, else show that text" seems to be way too high, for such a simple if statement, especially if it is included within a echo.

I've taught myself PHP, mostly using W3Schools, so things such as 'shortcode' etc was never 'taught' to me, so I spotted a shortcoded if statement in a module I was using in Drupal, and after researching it, I decided to do a short blog post on how it can be used, mostly for future reference, but to also share what I am learning.

Below, is an example of an if statment that is inside an echo, which usually looks like this:

   echo 'You are now viewing the '; 
   if(->nid==10) { echo 'Blog'; } else { echo ->title; }
   echo ' page'; 

This would usually print something along the lines of "You are now viewing the (pagename) page". As it is inside a echo, it requires ending the echo command (the semi-colon) starting an if statment, then finishing the echo afterwards, with another if command. You can cut this down with the following syntax for 'shorthand' PHP if statements[#], which can be included within echo commands:

(condition) ? /* value to return if condition is true */ 
           : /* value to return if condition is false */ ; 

So, the short version of our if statement above is as follows:

   echo 'You are now viewing the '.(->nid==10 ? 'Blog' : ->title).' page'; 

Using this will overall cut down the amount of code needed for your webapp.