skip to Main Content

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


  1. $x = false && print 'printed' || true;

    This run in two sets

    1. false && print 'printed' (short circuit expressions in PHP?)
    2. answer from 1. || true

    $x is true in this case


    Order of && and ||, or || and `&&

    • && (Logical AND): Higher precedence.
    • || (Logical OR): Lower precedence.
    Login or Signup to reply.
  2. 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 prints 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.

    Login or Signup to reply.
  3. Both && and || work only with boolean operands, .i.e., true and false. 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 evaluate print 'printed' || true and convert 1 to true. Then your actual expression is just false && true.

    If you are confused about why the || is part of the print operand, it’s because there are no parentheses to tell print that only the string should be the operand. print can also display values of other types such as boolean.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search