'AND' vs '&&' as operator

后端 未结 10 787
野性不改
野性不改 2020-11-22 02:42

I have a codebase where developers decided to use AND and OR instead of && and ||.

I know that there is a

10条回答
  •  轮回少年
    2020-11-22 03:31

    I guess it's a matter of taste, although (mistakenly) mixing them up might cause some undesired behaviors:

    true && false || false; // returns false
    
    true and false || false; // returns true
    

    Hence, using && and || is safer for they have the highest precedence. In what regards to readability, I'd say these operators are universal enough.

    UPDATE: About the comments saying that both operations return false ... well, in fact the code above does not return anything, I'm sorry for the ambiguity. To clarify: the behavior in the second case depends on how the result of the operation is used. Observe how the precedence of operators comes into play here:

    var_dump(true and false || false); // bool(false)
    
    $a = true and false || false; var_dump($a); // bool(true)
    

    The reason why $a === true is because the assignment operator has precedence over any logical operator, as already very well explained in other answers.

提交回复
热议问题