Member Avatar for arcticM

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?

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

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?

Member Avatar for diafol

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

Member Avatar for arcticM

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?!

Member Avatar for diafol

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.