Ternary Conditional Syntax in PHP

The below two statements are equivalent. The first uses the ternary syntax and the second uses the more traditional verbose syntax. The condition should be a statement or variable that evaluates to true or false. true will be executed if the condition is met. false is executed if the condition fails.

$var = [condition] ? [true] : [false];
if ([condition]) {
    $var = [true];
} else {
    $var = [false];
}

You could argue that the second method is more readable, but in certain instances, a one-liner can be better.


$isNew = false;
$output = $isNew ? 'New' : 'Not New';
print($output); 
//'Not New';

$isNew = true;
$output = $isNew ? 'New' : 'Not New';
print($output); 
//'New';

Snippets and tagged