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

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

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

5条回答
  •  执笔经年
    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
    

提交回复
热议问题