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?
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:
print "hello " && print "world";
// outputs "world1"; print "world" is evaluated first,
// then the expression "hello " && 1 is passed to the left-hand print
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 returns 1
), then probably the next operator ||
is evaluated next (left to right), so the whole expression is evaluated as if it were written
$x = false && (print 'printed' || true);
If you wrote it just a little bit different, it evaluates as you expected it, just according to operator precedence:
$x = false && 1 || true;
Here $x
is false
. So the difference is really the "language construct" nature of print
.