9

I want to share 1 question which is asked most of the time in interviews and I wasn't able to e answer that question, but finally I found the answer:

How to Swap 2 variable value without using 3rd variable??

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
Jay
  • 3,353
  • 5
  • 25
  • 34

2 Answers2

51

This method will work for any variable type:

$a = 5;
$b = 6;
list($a, $b) = array($b, $a);
print $a . ',' . $b;

Output:

6,5

Another simple way (which only works for numbers, not strings/arrays/etc) is

$a =  $a + $b;  // 5 + 6 = 11
$b = $a - $b;   // 11 - 6 = 5
$a = $a - $b;  // 11 - 5 = 6
print $a . ',' . $b;

Output:

6,5
Joe
  • 15,669
  • 4
  • 48
  • 83
Jay
  • 3,353
  • 5
  • 25
  • 34
9

Surely you want the XOR swap algorithm ? At least for numeric variables.

Conventional swapping requires the use of a temporary storage variable. Using the XOR swap algorithm, however, no temporary storage is needed. The algorithm is as follows:

X := X XOR Y

Y := X XOR Y

X := X XOR Y

Although I've never seen it used in real scenarios (beyond assembler work)

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440