Page 1 of 1

nuub question about weird PHP ^ operation error (solved)

Posted: Wed Jul 30, 2014 12:33 pm
by Gunner
my code is something like
<?php
echo (2^2);
?>

and the result is 0???? :shock:

alright another try..

echo (2^3);

the result is frickkin' 1!

idk whats wrong

Re: nuub question about weird PHP ^ operation error

Posted: Wed Jul 30, 2014 12:58 pm
by Chris
That's the Exclusive or (XOR) operator, I think you thought it was to get the power of. You need the pow() function for that.

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

Re: nuub question about weird PHP ^ operation error

Posted: Wed Jul 30, 2014 1:15 pm
by Gunner
ah sweet :D
the problem with that is IDK what is this symbol ^ called really..
I searched "what is ^" on google it does nothing, the query results are the same with "what is" so its like google didnt read the ^ :?

thanks broh

Re: nuub question about weird PHP ^ operation error (solved)

Posted: Wed Jul 30, 2014 4:29 pm
by Jackolantern
Google is not good with symbols, and many of them have a different meaning there. Anyway, XOR is a bitwise operator, meaning it works with the bits of a value. It stands for "exclusive or", meaning that a bit will be toggled (turned to 1) if and only if one of the two values is 1. Here is the "truth table" for xor:

A B | Result
0 0 | 0
1 0 | 1
0 1 | 1
1 1 | 0

You can see that the result is 1 only if one or the other bits is 1, but not if both are 1.

Here are the actual numbers you tried (you look at each number individually in each column to compare):

2^2 = 0

2: 0010
2: 0010
result: 0000 = 0

Any number XOR'd against itself will always be 0.

2: 0010
3: 0011
result: 0001 = 1

The only difference between these two numbers was the one's place, so it was the only one that "survived" the XOR'ing, giving you 1.