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.