Using the Ternary Operator in PHP

It took me a while to actually figure out the name of this type of operator since trying to search “PHP” and “question mark” didn’t really result in anything useful. You’ve probably seen the ternary operator used multiple times in code and just never really understood what it was and how it worked. All it is, is a simpler alternative to setting a variable using an if-else conditional statement.
We can take the following if-else conditional statement:

if ( 'on' == $value )
    $check = 'It is on';
else
    $check = 'It is off';

And replace it with a ternary operator to get this:

// The parentheses around the conditional statement are not required
// I just like to use them as a visual guide
$check = ( 'on' == $value ) ? 'It is on' : 'It is off';

That breaks down to:

$variable = ( condition ) ? true : false;

If the value of our $value variable equals ‘on’, then our $check variable will equal to ‘It is on’. Otherwise, it will equal to ‘It is off’.
Once you grasp how the ternary operator works it is a great tool to use to trim down your code and simplify your conditional statements.
Read more about the ternary operator on the PHP website.

Share this:

Email
Facebook
Twitter
Pinterest
Pocket

Premium Themes for WordPress

Looking for an easy-to-use Premium Theme for WordPress? Check out Themes by bavotasan.com and have your site up and running in no time.

Use this WordPress website builder to build powerful websites in no time for your or your clients.

WordPress Hosting

WP Engine – designed from the ground-up to support and enhance the workflow of web designers.

Bluehost – providing quality web hosting solutions since 1996.

About the author

Picture of Luke Perrie

Luke Perrie