I’m trying to understand why this expression:
$x = false && print 'printed' || true;
results in $x
being false
instead of true
. I know that &&
has higher precedence than ||
, but I’m confused about how the combination of &&
, ||
, and print
works here. Can someone explain the exact evaluation process, step by step, in terms of operator precedence and short-circuit evaluation?
3
Answers
$x = false && print 'printed' || true;
This run in two sets
false && print 'printed'
(short circuit expressions in PHP?)answer from 1. || true
$x
istrue
in this caseOrder of
&&
and||
, or||
and `&&With an example from the PHP manual for
print
and the comments from @Jakkapong Rattananen, @shingo and @Sergey Ligus I came to the following conclusion:
As
print
is a language construct, evaluation is a bit different there. The example is the following:This is similar to your expression, but differs in the way that two
print
s are used.So when the
print
after the&&
is evaluated first (and always returns1
), then probably the next operator||
is evaluated next (left to right), so the whole expression is evaluated as if it were writtenIf you wrote it just a little bit different, it evaluates as you expected it, just according to operator precedence:
Here
$x
isfalse
. So the difference is really the "language construct" nature ofprint
.Both
&&
and||
work only with boolean operands, .i.e.,true
andfalse
. All other types must be converted to a boolean first.print
is a language construct which returns an int. So in order to evaluate the expression, you must first evaluateprint 'printed' || true
and convert1
totrue
. Then your actual expression is justfalse && true
.If you are confused about why the
||
is part of theprint
operand, it’s because there are no parentheses to tellprint
that only the string should be the operand.print
can also display values of other types such as boolean.