Conditional Statements with PHP Shorthand

PHP shorthand can help clean up your template files and make small jobs, like echoing a tiny piece of text conditionally, much simpler.

Conditional statements (if/else) are very useful in all kinds of programming. These examples are tailored to front end usage like theme development / templating. This shorthand PHP technique is something I frequently looked up when I was a beginner to remind myself of the syntax.

It changes what was…

if ( $something ) :
echo "this";
echo "that";


echo ( $something ? "this" : "that" );

Practical Shorthand Usage

A common job I use conditional shorthand for, is remembering form data that was already entered.  So if the user has submitted a mistake, all their info is still visible and they don’t have to start again from scratch.

value="<?php echo ( $_POST['name'] ? $_POST['name'] : '' ); ?>"

You could also do something like this:

echo "Welcome ". ( is_user_logged_in() ? 'Old Friend!' : 'Guest.' );

This is very useful PHP technique to get the hang of and there are lots of different ways to put it to good use.

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>