Pergunta

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?

Foi útil?

Solução

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.

Outras dicas

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.';

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

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top