Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap two variables value without using third variable in php [duplicate]

Tags:

php

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??

like image 843
Jay Avatar asked Aug 21 '13 11:08

Jay


People also ask

How can I swap two variables without third variable in PHP?

Code: Swap two variables value without using third variable php $a = 15; $b = 276; echo "\nBefore swapping: ". $a . ',' . $b; list($a, $b) = array($b, $a); echo "\nAfter swapping: ".

Can we swap 2 variables without a third one?

Given two variables, x, and y, swap two variables without using a third variable. The idea is to get a sum in one of the two given numbers. The numbers can then be swapped using the sum and subtraction from the sum.


2 Answers

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
like image 141
Jay Avatar answered Oct 19 '22 19:10

Jay


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)

like image 22
Brian Agnew Avatar answered Oct 19 '22 18:10

Brian Agnew