Swap Values Without A Third Variable In PHP
Tue, 08/19/2008 - 15:45 | by philipnorton42
Swapping variable values is important in sorting algorithms when you want to swap a higher value with a lower one. The usual action of variable assignment is to take the first value, put the value of this variable in a temporary variable and then assign the value of the second variable to the first one. As in the following code:
$tmp = $a; $a = $b; $b = $tmp;
This can be rewritten using the bitwise Xor (exclusive or) operator.
$a = $a ^ $b; $b = $b ^ $a; $a = $a ^ $b;
This can also be written in the shorthand notation as follows:
$a ^= $b; $b ^= $a; $a ^= $b;
Comments
Post new comment