-1

IN php, how do the following operands work?

^ |

e.g. $a = 11; $b = 7; echo $a ^ $b;

outputs 12

and

    $a =    11;
$b =    7;
echo $a | $b;

outputs 15

Im not sure why in each case. Can someone please shed some light?

Kevin Bradshaw
  • 6,122
  • 11
  • 45
  • 73
  • 6
    http://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php – Kemal Fadillah May 09 '12 at 21:39
  • Whats with the down votes? I get that this has been asked before, but unless I knew to look for bitwise operators this would have been impossible to search for. If you are down voting please leave a reasonable explanation for doing so – Kevin Bradshaw May 10 '12 at 09:01

3 Answers3

4

Those are bitwise XOR and OR.

$a = 11; // 1011
$b =  7; // 0111

With XOR each bit that is different in $a and $b becomes a 1, the bits that are the same become a 0.

$a ^ $b: // 1100 = 12

With OR each bit that is a 1 in either $a or $b becomes a 1, in this case all the bits.

$a | $b: // 1111 = 15

There is also an AND equivalent: $a & $b: // 0011 = 3

A full list of PHP's bitwise operators.

Paul
  • 130,653
  • 24
  • 259
  • 248
3

They are bitwise operators.

http://php.net/manual/en/language.operators.bitwise.php

Basically these are used for binary data. These are used quite often to combine a series of flags within a single integer. For instance, if I had two flags:

FLAG1 = (binary)'1' = (integer)1
FLAG2 = (binary)'10' = (integer)2

I could combine the two using a bitwise operator:

$combined_flags = FLAG1 | FLAG2 = (binary)'11' = (integer)3

Then I could check if one of the flags is set using a bitwise operator as well:

if ($combined_flags & FLAG1) echo 'flag 1 is set to true.';
dqhendricks
  • 17,461
  • 10
  • 44
  • 80
0

They are bitwise operators, this means they operate on binary numbers.

11 is 1011 in binary, and 7 is 0111.

^ is XOR. For each bit in both values, it returns 1 if they are different.

11 ^ 7 = 1011 ^ 0111 = 1100 = 12

| is OR. For each bit in both values, it returns 1 if at least one is 1.

11 | 7 = 1011 | 0111 = 1111 = 15

More info: http://php.net/manual/en/language.operators.bitwise.php

Rocket Hazmat
  • 204,503
  • 39
  • 283
  • 323