Click to See Complete Forum and Search --> : ^=


bokeh
01-13-2006, 04:17 AM
Example: $variable ^= 1;

What is ^= ?

NogDog
01-13-2006, 10:41 AM
It's doing a bitwise XOR comparison of the two values and assigning the result to the first value.

bokeh
01-13-2006, 10:58 AM
Can you write it out longhand to help me picture it? I mean it's a shortcut, isn't it? $variable has a 0 or 1 value and this code flips it. I just can't see it.

chazzy
01-13-2006, 11:02 AM
$a = 1010 ^ 1001;
echo $a;

NogDog
01-13-2006, 11:25 AM
$a ^= $b; is the same as $a = $a ^ $b; where the result is, "Bits that are set in $a or $b but not both are set." (http://www.php.net/manual/en/language.operators.bitwise.php).

$a = 12;
$a ^= 9;
echo $a;
/* returns 5 because:
12 = binary 1100
9 = binary 1001
XOR = binary 0101 = decimal 5

http://irc.essex.ac.uk/www.iota-six.co.uk/c/e4_bitwise_operators_and_or_xor.asp has some useful info and examples on bitwise comparisons.

bokeh
01-13-2006, 11:26 AM
Is it like this:$i = 0;
$i = $i ^ 1;
echo $i; // 1
$i = $i ^ 1;
echo $i; // 0

chazzy
01-13-2006, 11:30 AM
Is it like this:$i = 0;
$i = $i ^ 1;
echo $i; // 1
$i = $i ^ 1;
echo $i; // 0

yep pretty much.

Edit: I just noticed that it won't take binary input, has to be string/int literals. hmpf. makes sense why my post gave me 27 and i was like O_O;;

NogDog
01-13-2006, 11:31 AM
Is it like this:$i = 0;
$i = $i ^ 1;
echo $i; // 1
$i = $i ^ 1;
echo $i; // 0
Yes.

NogDog
01-13-2006, 11:34 AM
Note: if the values involved are strings, then the binary form of the ascii value of each character is used, so 2 ^ 4 is different from "2" ^ "4".