note 105142 deleted from language.variables.basics by danbrown
| From: | danbrown@php.net | Date: | Mon, 01 Aug 2011 13:51:31 +0000 |
| Subject: | note 105142 deleted from language.variables.basics by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-182065@lists.php.net to get a copy of this message | ||
Note Submitter: gene dot garber at gmail dot NOSPAM
----
The XOR note above stated the content was switching but I don't think switching or swapping the
variable data is a detailed way to explain the code there.
<?php
$a = 3;
$b = 5;
$a^=$b;
/**
~binary (unary operator)~
$b 0000 0101 a/k/a 5
$a 0000 0011 a/k/a 3
=either or but not both=
$a 0000 0110 a/k/a 6
~~
*/
$b^=$a;
/**
~~
$a 0000 0110 a/k/a 6
$b 0000 0101 a/k/a 5
=either or but not both=
$b 0000 0011 a/k/a 3
~~
*/
$a^=$b;
/**
~~
$b 0000 0011 a/k/a 3
$a 0000 0110 a/k/a 6
=either or but not both=
$a 0000 0101 a/k/a 5
~~
*/
?>
so now $a=5, $b=3
I think it would be less confusing to just do a regular swap (see below) but does XOR make it
possible to always swap variable data without the extra variable ($temp)?
<?php
$a=3;
$b=5;
$temp = $a;
// $temp = 3;
$a = $b;
// $a = 5;
$b = $temp;
// $b = 3;
// $a = 5, $b = 3, ($temp cries itself to sleep)
?>