Swap Values Without A Third Variable In PHP

19th August 2008 - 1 minute read time

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;

Add new comment

The content of this field is kept private and will not be shown publicly.