What is the difference between the | and || operators?

前端 未结 5 770
鱼传尺愫
鱼传尺愫 2020-12-02 01:41

| and || - what is the difference between these two operators in PHP?

相关标签:
5条回答
  • 2020-12-02 02:06

    | -> binary operator || -> Boolean operator or -> also a Boolean operator with lower precedence

    $x = false | true; //will set $x to an integer
    $x = false || true; //will set $x to true
    $x = false or true; //will set $x to false exactly the same that:
    ($x = false) || true;
    
    0 讨论(0)
  • 2020-12-02 02:16

    Just like the & and && operator, the double Operator is a "short-circuit" operator.

    For example:

    if(condition1 || condition2 || condition3) If condition1 is true, condition 2 and 3 will NOT be checked.

    if(condition1 | condition2 | condition3) This will check conditions 2 and 3, even if 1 is already true. As your conditions can be quite expensive functions, you can get a good

    performance boost by using them.

    There is one big caveat, NullReferences or similar problems. For example:

    if(class != null && class.someVar < 20) If class is null, the if-statement will stop after "class != null" is false. If you only use &, it will try to check class.someVar and you get a

    nice NullReferenceException. With the Or-Operator that may not be that much of a trap as it's unlikely that you trigger something bad,

    but it's something to keep in mind.

    No one ever uses the single & or | operators though, unless you have a design where each condition is a function that HAS the be

    executed. Sounds like a design smell, but sometimes (rarely) it's a clean way to do stuff. The & operator does "run these 3 functions,

    and if one of them returns false, execute the else block", while the | does "only run the else block if none return false" - can be useful,

    but as said, often it's a design smell.

    0 讨论(0)
  • 2020-12-02 02:17

    | is a bitwise or, || is a boolean or.

    0 讨论(0)
  • 2020-12-02 02:21

    Meaning

    | is binary operator, it will binary OR the bits of both the lefthand and righthand values.

    || is a boolean operator, it will short circuit when it encounters 'true' (any non-zero value, this includes non-empty arrays).

    Examples

    print_r(1 | 2)  // 3
    print_r(1 || 2) // 1
    

    When used with functions:

    function numberOf($val) {
        echo "$val, ";
        return $val;
    }
    
    echo numberOf(1) | numberOf(2);  // Will print 1, 2, 3
    echo numberOf(1) || numberOf(2); // Will print 1, 1
    
    0 讨论(0)
  • 2020-12-02 02:29

    | operates on the bits of a variable: 2 | 4 = 6

    || operates on The Boolean value of a variable: 2 || 4 = TRUE

    0 讨论(0)
提交回复
热议问题