3

Possible Duplicate:
Reference - What does this symbol mean in PHP?

Whats the difference between these two in php?

 if( $x==1 || $y==1)   if( $x==1 && $y==1)

vs. (respectively)

 if( $x==1 | $y==1)    if( $x==1 & $y==1)

To my knowledge they both work the same | vs. || in php. But there has to be a difference!!!

Community
  • 1
  • 1
Arian Faurtosh
  • 17,987
  • 21
  • 77
  • 115

5 Answers5

6

|| and && are boolean operators, they take 2 arguments, convert each to a boolean, then return true or false.

| and & are bitwise operators. They convert their arguments to binary and compare each bit. They return a binary number.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • clear and concise! perfect! Thanks! – Arian Faurtosh Nov 20 '12 at 16:28
  • 1
    @Arian, also note that `||` and `&&` evaluate their arguments from left-to-right and short-circuit as soon as possible, that is, if the left expression is true, `||` will not evaluate anything to the right (same for false and `&&`). – acelent Nov 25 '12 at 00:32
2

One is using conditional or and and and the other is using bitwise or and and.

alex
  • 479,566
  • 201
  • 878
  • 984
1

|| this is condition OR
| this is bit wise or

  1. $a | $b Or (inclusive or) Bits that are set in either $a or $b are set
  2. $a & $b And Bits that are set in both $a and $b are set.

.

              if( $x==1 || $y=1)             if( $x==1 && $y==1)

  if body --> if one of them is true            both is true
NullPoiиteя
  • 56,591
  • 22
  • 125
  • 143
0

First off: if( $x=1 || $y=1) will set $x to the value of 1 and $y to the value of 1.

The correct syntax would be:

if( $x==1 || $y==1)

The difference can be better expressed with words:

if( $x==1 OR $y==1) `if( $x==1 AND $y==1)

The double ampersand and double pipes are known as logical operators. see more here

The single ampersand and single pipes are bitwise statements. see more here

Samuel Cook
  • 16,620
  • 7
  • 50
  • 62
0

Documentation is your friend. && and || are logical operators. You can read more about them here.

I highly suggest you read about operator precedence and learn why && vs and and || vs or are different. Learn when one is more appropriate than the other. Essentially = has higher precedence than and and or, but lower precedence than && and ||. Example #1 of the logical operators section does a good job of explaining this.

With other languages you just have && and ||, not and and or.

& and | are bitwise operators. You can read about them here.

Typical usage for bitwise operators are flags. One common use is PHP's error_reporting setting.

Luke
  • 13,678
  • 7
  • 45
  • 79