short PHP if statement written in one line (ternary operator)

Its an easy way to write short If-Statements in PHP, also known as the ternary operator.
Ternary because of the three operands: a condition, a result for true, and a result for false.

But I always need to look up this snippet, so now I write it down for reference.

$notice = ($price < 20) ? 'cheap' : 'expensive';

This code is equal to this:

if($price < 20) {
    $notice = "cheap";
}
else {
    $notice = "expensive";
}

If the variable “price” is less than 20, the variable “notice” is set to “cheap”.
Otherwise (price is equal, or greater than 20) the notice is set to “expensive”.

Leave a Reply