Change the value of two variables without using a third variable in php

I want to share one question that is most asked in the interview, and I could not answer this question, but finally I found the answer:

How to replace the value of variable 2 without using a third variable

+7
php
source share
2 answers

This method will work for any type of variable:

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

Output:

 6,5 

Another easy way (which works only for numbers, not strings / arrays / etc) -

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

Output:

 6,5 
+32
source share

Of course you want an XOR exchange algorithm ? At least for numeric variables.

Normal swap requires the use of a temporary variable storage. However, the use of the XOR folding algorithm does not require temporary storage is necessary. The algorithm is as follows:

X: = X XOR Y

Y: = X XOR Y

X: = X XOR Y

Although I have never seen it used in real-world scenarios (other than assembly work)

+8
source share

All Articles