Many times I asked this particular question in the interview session and many people failed to answer. This is just to see the analytic ability of a candidate and how dynamic thinking they have. The logic is same for all programming language, so if you have the logic right then you can answer it for any particular language such as PHP, JAVA, C++, C etc. but in this tutorial We will use PHP π
What if we can use the third variable:
$a = 100;
$b = 200;
now we need to swap the values so that $a becomes 2oo and $b becomes 1oo.
the basic technique is to introduce a third variable $tmp
$tmp = $a;
$a = $b;
$b = $tmp;
isn’t it straight forward. introducing a third variable it is so easy. but what will be our approach if there is no third variable? is it possible?
The answer is a big YES. There are several ways and they fall in two types of solution.
1. Arithmetic operation
2. Bitwise operation.
Arithmetic Operation:
we can use addition-deduction and multiply-division method to solve the problem.
let’s see how addition – deduction method works.
<?php
$x = 10;
$y = 20;
$x = $x+$y;
$y = $x – $y;
$x = $x – $y;
?>
it is also very simple, isn’t it. first we are adding the two numbers and keeping the result in one of the variable. in the above example its $x and it contains $x+$y. in the second operation, we are deducting $y from $x and assigning it to $y. now lets break the equation logically
$y = $x – $y => $x + $y – $y => $xΒ // [ since $x = $x+$y ]
cool, we swapped one of the variable. and following the same operation we are swapping the second one in the third line. so that’s it. It is so easy but just requires some logical thinking. do not try to memorize it rather than understand the simple logic here.
now the multiply-division method:
<?php
$x = 10;
$y = 20;
$x = $x*$y;
$y = $x / $y;
$x = $x / $y;
?>
it is same as the addition-deduction method and logic is similar.
now do we see any problem in the above logic? that is the question i ask if someone can answer the question correctly and show me the above solution. π
the answer for that is very simple, it is the number overflow as we always have upper limit for integers. so when we add or multiply two big numbers then the result can cause overflow and might not show desired results.
so what can be a good solution with keeping the overflow fact in mind? the answer is bitwise operation
Bitwise operation:
in order to swap two values we can use the XOR bitwise operator.
Note: A bitwise exclusive or takes two bit patterns of equal length and performs the logical XOR operation on each pair of corresponding bits. The result in each position is 1 if the two bits are different, and 0 if they are the same
the algorithm is
x = x XOR y
y = x XOR y
x = x XOR y
if we write them in computer language using caret (^) then it will look like
x = x ^ y
y = x ^ y
x = x ^ y
in shorter version:
x ^= y
y ^= x
x ^= y
in one line
x ^= y ^= x ^= y
so here is the command in php:
$x ^= $y ^= $x ^= $y
now how it works:
so now we know how to swap two values without using a third variable. ask me any questions you have π
Thanks!!!!!
Multiply and division method suffers from integer overflow as discussed in this post about How to swap two numbers without temp variable, See comment section, it also has problem when one of the number is zero because divide by zero…..
Nice solution……….
π
really nice solution.
Simple but very important thing ! thanks Mizan bhai ….
very interesting solution…..indeed !! thanks mizan vai.
Nice one, this is simple and common but very important and most important thing is you have put many ways in on post.
BIG HUG
here’s another one
list($a, $b) = array($b, $a)
it will also swap values of two variables without using a third one π – the php way!
And it will work for every data type in PHP.
HI.
THIS CODE IS ONLY ONE TIME RUN.BUT ANOTHER TIME DID NOT RUN.SO GIVE SOLUTION
Smart Work!! Good One.
π thanks boss.
thanks boss, nice post. Cool tricks, may be on next interview i may need this.
i was asked this very same question on a test before. back then i had no idea how to do.
thanx
Thanks Mizan this is really a nice stuff for the begginers like me.
A cunning question to be asked in an interview. Are you familiar with something called ‘Principle of least astonishment’? In any job interview, I believe, an interviewer should only assess a person’s interest and skills. By the way, I am aware of this trick since 2000/2001 and I don’t earn my living writing code.
Hi Shuvo
For developers who earn their living writing codes, these type of questions are very common. we have to face so many different type of questions which are outside of our interest. I completely agree with you that interview should assess only person’s interest and skills but in programming basic is also very important and this question is a basic one π
Thanks for the post.. i just want to add more…
Using Arithmetic Operation it just can swap int or float type data.
But if we use Bitwise operation it can swap both number and string.
But it cannot swap any array, class; But if we use List it can swap everything. It can swap number, string, array and also can swap a class ο
Array swap sample :
‘one’);
$y = array(‘b’ => ‘two’);
list($x,$y) = array($y,$x);
echo ‘X : ‘;
print_r($x);
echo ‘Y : ‘;
print_r($y);
?>
Output:
X :
Array
(
[b] => two
)
Y :
Array
(
[a] => one
)
Class swap :
<?php
class a
{
public $name = ‘alu’;
}
class b
{
public $name = ‘begun’;
}
$x = new a();
$y = new b();
list($x,$y) = array($y,$x);
echo ‘X : ‘;
var_dump($x);
echo ‘Y : ‘;
var_dump($y);
?>
so list is better … π
mizan bhai 1st comment ta muse den pls.. tag er jonno tikmoto aseni..
Hi Apu
Using a list /array is almost similar to using a variable. π
we do not need to swap string, numbers will be good enough π
And please notice that on 32bit boxes it will only work for numbers smaller than 2 in the power 31 minus 1:
2147483647
see this code as example:
<?
$a=pow(2,31);
$b=pow(2,31)-1;
echo “$a $bn”;
$a^=$b^=$a^=$b;
echo “$a $bn”;
notify-me (sorry)
Very cool post…
Thanks Mizanur Rahman…..plz send me interview questions with answers for 1.5 years in php mysql.
and also send how to learn open source like joomla,drupal……
Thanks & regard
rakeshsingh1983@gmailk.com
Mizan Bhai,I always monitor your bolg.When u post anything then i read this & get idea various terms in PHP.This is very nice post.
Thanks Mizan Bhai.
i need swapping in php with different methods.
hai miza,
thanks for your code, please give me a solution for studying linked list easily.
loving friend,
sumesh
thanks machi……..
THANKS FOR THE NICE METHOD
thanks bhaya ………a lot actually i have studied pre-med , nw i am fcing a little bt prblem in prgraming my teachr had given me thies question and i was searching for it from many days …………….thanks …
Salam …..
Thanks Mizanur Rahman bhaiβ¦..plz send me interview questions with answers for 1.5 years in php mysql.
and also send how to learn open source like joomla,drupalβ¦β¦
Thanks & regard
a_deen@rocketmail.com
i would like to join me to you!
very good logic i am new learner of PHP and i am trying to understand how to swap
dear friends i am new learner kindly see my method of equation
<?php
$a ='100';
$b='200';
$c= $a + $b;
$b= $c-$a;
echo "a is equal to $b “;
$b= $c-$b;
echo “b is equal to $b”;
?>
great info here
This is called programming. I thundered.
Yesterday,in a job interview they asked me same question to swap values without usind a third variable, even though I was very close I couldn’t come up with correct solution. And now I see how it is easy… I wish I knew the solution before.NΔ°CE AND NEAT
Here is another simple one
a=b-a+(b=a) ;
thanks for reply
thanks.used me in a gud way
how can we swap 2 no.s by using only one equation?
thanks a lot
thanku
awesome
Very nifty and well explained.
You can do this in one statement – a = ((a + b) – (b=a))
Excellent!!!!!
Excellent!!!!
really nice..
nice ….. solution
Thank u very much….
what happen if we take first number as smaller than second number
nice………….
thank u………….
nice……….
good one …
what about using extract for swapping?
extract(array(‘a’=>$b, ‘b’=>$a))
or
list($a, $b) = array($b, $a);
I like this explanation
So nice answer
how to swap values of three avriable if a->b->c->a
Thanx 2 make it clear.
thank you!
big help thx
now you had seen this example with 2 – 3 statements
so i give you optimum sol by solving in 1 line statement
are-
a=a+b-(b=a);
or
a=a*b/(b=a);
amitvaishnava
It is helpfull 4 me
good information.thnx!!!!
goodiii……
good methods for beginner….thanks