Sep.25

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 : [php] < ?= $my_variable ? > [/php] 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 : [php] if ($home === TRUE) { echo 'You are home.'; } else { echo 'You are not home.'; } [/php] The shorthand method for this would be as such : [php] echo ( $home === TRUE ? 'You are home.' : 'You are not home.'); [/php] 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 : [php] if ($home === TRUE) { echo 'You are home.'; } else { echo 'You are not home.'; } [/php] INTO [php] < ?= ($home === true ? 'You are home.' : 'You are not home.')? > [/php] This shorthand can be dropped in your HTML and used directly. I personally use PHP *AS* my templating system, so this becomes very handy.

Programming,PHP

Leave a comment