The ? Operator

One way of avoiding the verbosity of if and else statements is to use the more compact ternary operator, ?, which is unusual in that it takes three operands rather than the more usual two.

$fuel = 2;
echo $fuel <= 1 ? "Fill tank now" : "There's enough fuel";

In this statement, if there is one gallon or less of fuel (in other words $fuel is set to 1 or less), the string “Fill tank now” is returned to the preceding echo statement. Otherwise, the string “There’s enough fuel” is returned.


You may also like...