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:

  1. $tmp = $a;
  2. $a = $b;
  3. $b = $tmp;

This can be rewritten using the bitwise Xor (exclusive or) operator.

  1. $a = $a ^ $b;
  2. $b = $b ^ $a;
  3. $a = $a ^ $b;

This can also be written in the shorthand notation as follows:

  1. $a ^= $b;
  2. $b ^= $a;
  3. $a ^= $b;

Add new comment

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