Logical and Precedence

Something I was previously unaware of:

The reason for the two different variations of “and” and “or” operators is that they operate at different precedences.

PHP’s && vs. and have different precedence? Who thought this was a smart idea? What end or purpose could it possibly serve?

Yet another one of the things that just makes me smack my head. It does explain a few things — why I couldn’t do variable setting as I might in Perl, a la:

$var = $test || $default;

In this case, the test occurs first, setting $var = 1; Had I used:

$var = $test or $default;

All would have been fine.

How can someone think this is sane?

One Response to “Logical and Precedence”

  1. Timwi Says:

    Now I’m somewhat surprised about this. As much as I hate disagreeing with an anti-PHP statement, but:

    • I can’t believe you would want for “$var = $test || $default;” to do the assignment first. That runs contrary to intuitive expectation as well as C/C++/C#/Java/everything else.
    • I’m surprised you ask “Who thought this was a smart idea?” when the answer is probably Larry Wall. The “two AND/OR operators with different precendence” idea comes from Perl, and PHP has copied it. PHP may have messed up other precedences (I wouldn’t be surprised), but the statement that = has a higher precendence than or but a lower precendence than || applies both to PHP and to Perl.