2

In PHP, why false and (true && print('hi')) evaluates to false and doesn't print 'hi'? I know logical operators evaluates in short-circuit (they're lazy), but && and parenthesis has upper precedence than and, so (true && print('hi')) should be evaluated first.

Any clues? Thanks!

7
  • @CBroe it not the same.he is asking its not working with "true" when considering operator precedence.
    – nithinTa
    Oct 21, 2017 at 8:55
  • 2
    @tan yes it is. The question "does the condition after && (or and, as here) always get evaluated" gets answered with No for false and something - the something does not even get looked at any further than necessary. Operator precedence does mean what influence the operator has on the result of the expression, not necessarily evaluation order of the individual sub-expressions.
    – CBroe
    Oct 21, 2017 at 9:03
  • 2
    Not sure why these hypothetical questions come up, if I wrote this code whilst working for a company I would expect to be kicked out, not voted up on SO.
    – Nigel Ren
    Oct 21, 2017 at 9:22
  • @CBroe I read again and again to understand and digest this line "Operator precedence does mean what influence the operator has on the result of the expression, not necessarily evaluation order of the individual sub-expressions" an old school mistake. Thanks CBroe & Ricardo Pérez López
    – nithinTa
    Oct 21, 2017 at 9:39
  • 1
    @NigelRen because people want to learn???
    – ishegg
    Oct 21, 2017 at 11:16

2 Answers 2

0

It's actually a good test example to play with to show the order of evaluation.

Evaluation is performed from left to right.

So to add something to your example...

<?php

// Evaluates Left to right
// Prints HI as (true && print('Hi') evaluates as TRUE
// Then the && FALSE is tested and it fails
if((true && print('Hi')) && FALSE){
    echo 'Success';
} else {
    echo 'Failed';
}

// Evaluates Left to right
// FALSE is evaluated and Fails
// No further checking is performed
if(FALSE && (true && print('Hi'))){
    echo 'Success';
} else {
    echo 'Failed';
}

Note: I've not put in the AND vs && but you get the same results.

0

I can see the following in http://php.net/manual/en/language.operators.precedence.php:

Operator precedence and associativity only determine how expressions are grouped, they do not specify an order of evaluation. PHP does not (in the general case) specify in which order an expression is evaluated and code that assumes a specific order of evaluation should be avoided, because the behavior can change between versions of PHP or depending on the surrounding code.

So, I tested the following:

print('one') and (1 + print('two'))

and it prints:

onetwo

so PHP evaluates first the and's left operand even + has higher priority and even using parenthesis. Interesting!

Thanks to everybody.

Not the answer you're looking for? Browse other questions tagged or ask your own question.