I'm working on Expression parser and I would like add conditional operator (?:
) I've changeed &&
and ||
to act like the onces in javascript, using this code:
case '&&':
$stack->push($op1 && $op2 ? $op2 : ($op1 ? $op2 : $op1)); break;
case '||':
$stack->push($op1 ? $op1 : $op2); break;
so I thought that I just replace foo ? bar : baz
by foo && bar || baz
is it possible using regex? if operators can be nested, each argument to conditional operator can have same operator.
foo && bar || baz
and foo ? bar : baz
are not equivalent.
Suppose both foo
is a value considered to be true and bar
is a value considered to be false. In that case, foo && bar
is false, so the value of the first expression is baz
. The ternary operator (?:
), on the other hand, alwys returns the second argument when the first argunent is true, so it will return bar
.
Try 1 && 0 || 2
and 1 ? 0 : 2
. The first is 2 and the second 0.
The simplest way to evaluate the ternary operator is as a single operator taking three operands
By the way, op1 && op2
could be written much more simply as op1 ? op2 : op1
.