The ?:
operator is a ternary operator called the conditional operator.
It is conditional because the expressions expr2 and expr3 in expr1 ? expr2 : expr3
are evaluated based on the evaluated return value of expr1:
- If expr1 evaluates to true, expr2 is evaluated and the return value of expr2 is the return value of the whole
?:
operator expression;
- otherwise expr3 is evaluated and the return value of the
?:
operator expression is the return value of expr3.
Here’s an example:
echo 1 == 1 ? "true" : "false";
If 1 == 1
evaluates to true, "true"
will be echoed, otherwise "false"
.
Note that the ?:
operator is just a and not the ternary operator. The word ternary just means that there are three operands (op1 ? op2 : op3
) just like a binary operator has two operands (e.g. op1 + op2
, op1 / op2
, op1 % op2
, etc.) and unary operators just have one operand (e.g. !op
, -op
, ~op
, etc.).