Swap Values Without A Third Variable In PHP

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.
10 + 0 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.