Shorthand if/else statements in PHP & JS

Last modified March 10, 2019
.* :☆゚

Ternary operators are shorthand ways of writing an if/else statement.

Both PHP and JS have their own shorthand, and the snippets below are the most used techniques I use everyday to code faster.

The caveat of using ternaries however is that can get messy very quickly, making debugging that much more tiresome.

My policy is to just keep the statement short and simple. If it looks complicated to you, it’ll probably be 200x more complicated to someone else reading it.

If in doubt, always use if/else or switch.

PHP Ternary operator


//instead of writing this:
if ($condition) {
    echo 'hello';
else {
    echo 'goodbye';

//you can write this:
echo ($condition) ? /*if condition is true */ 'hello' : /*if condition is false*/ 'goodbye' ;
//or this, if the echo result is the same as the condition
echo ($condition) ?: 'hello';

//real world examples
echo (is_page('home')) ? 'Welcome' : the_title(); //if on the home page, display 'Welcome'. If not, display the_title();
$alt_tag = (get_post_meta($id, '_wp_attachment_image_alt')[0]) ?: get_post($id)->post_title; //if an alt tag is set on the image, display it. If not, display the image title instead.

JavaScript is pretty similar in usage.

JS Ternary operator

//instead of writing this:
if (condition) {
    return 'hello';
else {
    return 'goodbye';

//you can write this:
var result = condition ? 'hello' : 'goodbye';

// real world example
var device = $window.width() > 768 ? 'desktop' : 'mobile'; //if the browser viewport is less than 768px, set device to mobile. Otherwise, set it to desktop.

//You can also stack multiple conditions like below:
var num_photos = $(window).width() > 1100 ? 8 
                 : $(window).width() > 768 ? 6 
                 : 4;
//this is the same as writing an if/else if statement

Another useful bit of JS shorthand is the OR operator.

var greeting = title || 'goodbye';
//this statement assigns 'goodbye' as the default value. If a title is truthy, it will return the title. If a title is false, it will return 'goodbye'.

//real world example
const project = args.project || 'base', //project will return 'base' if args.project returns false