Quickest IF-THEN-ECHO-ELSE-ECHO in PHP

There is a trick used in PHP that I see for “If this, then echo this, else echo that“. This trick uses two short-hand methods of PHP simitaniously to create an easy, extra short-hand version of what can be a sizable logic structure.

First is the PHP shorthand for breaking out of HTML, into PHP, and printing a PHP variable. This normal, or long way of doing this is :

echo $my_variable;

The shorthand version uses the opening tag of “< ?=" , which is shorthand for "< ? echo ..." So the exact same results could be gained from :

< ?= $my_variable ? >

Note there is no need to terminate the string with a semicolon, as no parsable PHP is expected beyond our single expression.

The next shorthand method is the IF/THEN/ELSE. Normal or old PHP would look like :

if ($home === TRUE) {
echo 'You are home.';
} else {
echo 'You are not home.';
}

The shorthand method for this would be as such :

echo ( $home === TRUE ? 'You are home.' : 'You are not home.');

This quickly translates into ( CONDITION ? TRUE : FALSE ). We can now combine our two shorthands to make a quick switch in our HTML :

Now we can turn :

if ($home === TRUE) {
echo 'You are home.';
} else {
echo 'You are not home.';
}

INTO

< ?= ($home === true ? 'You are home.' : 'You are not home.')? >

This shorthand can be dropped in your HTML and used directly. I personally use PHP *AS* my templating system, so this becomes very handy.

Leave a Reply