so i checkied how to swap 2 variables without a 3rd one and I found this solution -

``````\$x ^= \$y ^= \$x ^= \$y;
``````

but I don't understand what the xor (^) does! never used it before and php.net has some strange examples I don't get..

can someone explain to me what is this thing and how it works?

3
Contributors
4
Replies
5
Views
6 Years
Discussion Span
Last Post by diafol

TRUE if either \$a or \$b is TRUE, but not both.

so, here's an example:

``````<?php
\$a = true;
\$b = true;
\$c = false;

echo (\$a xor \$b) ? 'true':'false'; # output: false because \$a and \$b are both true
echo (\$a xor \$c) ? 'true':'false'; # output: true because \$a is true, but not \$c
?>
``````

the above can be written also like this:

``````<?php
if(\$a xor \$b) { echo 'true'; } else { echo 'false'; }
?>
``````

ok?

Edited by cereal

Example
If you have two variables (\$a and \$b), which for the sake of argument can each be true or false.
Logical operators AND / OR will return TRUE if:

AND: ONLY when \$a AND \$b are both true
OR: When either \$a OR \$b is true OR when both are true
XOR: Only when either \$a OR \$b is true BUT NOT when both are true

I get the flaseXtrue=true..
what I don't get is what happens when the var isn't boolean.

here's an example from php.net

``````<?php
echo 12 ^ 9; // Outputs '5'

echo "12" ^ "9"; // Outputs the Backspace character (ascii 8)
// ('1' (ascii 49)) ^ ('9' (ascii 57)) = #8

echo "hallo" ^ "hello"; // Outputs the ascii values #0 #4 #0 #0 #0
// 'a' ^ 'e' = #4

echo 2 ^ "3"; // Outputs 1
// 2 ^ ((int)"3") == 1

echo "2" ^ 3; // Outputs 1
// ((int)"2") ^ 3 == 1
?>
``````

what is all of this?! how did they come up with 12^9 outputs a 5?!

You need to look at binary:

12 = 1100
9 = 1001

XOR
The exclusive either/or bits here: 0101
The 1000 isn't as it's common to both numbers
101 binary = 5 in decimal