Attributed to Solomon W. Golomb; A method for swapping the values of both of the variables without using an intermediate variable (your can tell this dates From the Elder days, when variables were expensive!). Thanks to PHP ' s syntax It's also a one-liner.
$a ^= $b ^= $a ^= $b;
Okay, here's how it goes (yeah, like I need to make content-free posts just for the sake of an increment ...).
First, simplify the line; Noting that ^= was right-associative, which means that's on that line the rightmost operator was evaluated first, that's the Ignment operators also return the value of the they assign to their lvalue, and that Foo^=bar was shorthand for Foo=foo^bar:
Code:
$a ^= $b ^= $a ^= $b;
$a ^= ($b ^= ($a ^= $b));
$a = $a ^b;
$a ^= ($b ^= $a);
$a = $a ^ $b;
$b = $b ^ $a;
$a = $a ^ $b;
Recall what ^ does. Takes each pair of corresponding bits from their arguments (the internal binary representation of its arguments, which is), a nd xors them together to produce the corresponding bit of the result ("corresponding" means that the first bits of both AR Guments produce the first bit of the result, the second bits of both arguments produce the second bit of the result, and S O on. This was why, as Buzzly noted, it's important that both variables was the same size-demons probably start flying out of Y Our nose if one of them runs out of bits to XOR before the other. Does to a pair of variables, we have need to recap what it does to single bits
http://www.bkjia.com/PHPjc/445164.html www.bkjia.com true http://www.bkjia.com/PHPjc/445164.html techarticle attributed to Solomon W. Golomb; a method for swapping the values of the----variables without using an intermedia Te variable (you can tell this dates from the Elder days ...