# How to SWAP values of two variables without using a third variable (integer) ?

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 🙂

Posted in: PHP

## 68 thoughts on “How to SWAP values of two variables without using a third variable (integer) ?”

1. Yunus says: Thanks!!!!!

• Anubhav says: 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…..

2. zia says: Nice solution……….

🙂

3. Arafat Rahman says: really nice solution.

4. Junal says: Simple but very important thing ! thanks Mizan bhai ….

5. lizzeelike says: very interesting solution…..indeed !! thanks mizan vai.

6. Ashraf says: 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

7. hasin says: 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!

• Stanis says: And it will work for every data type in PHP.

• sundar says: HI.
THIS CODE IS ONLY ONE TIME RUN.BUT ANOTHER TIME DID NOT RUN.SO GIVE SOLUTION

• Parveen Chauhan says: Smart Work!! Good One.

8. booleandreams says: 🙂 thanks boss.

9. lavluda says: thanks boss, nice post. Cool tricks, may be on next interview i may need this.

10. boes says: 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.

12. Shuvo says: 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.

13. mizan says: 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 😉

14. Tarek Mahmud apu says: 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 … 🙂

15. Tarek Mahmud apu says: mizan bhai 1st comment ta muse den pls.. tag er jonno tikmoto aseni..

16. booleandreams says: 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 🙂

17. rune_kg says: 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”;

18. rune_kg says: notify-me (sorry)

19. \$@!ful says: Very cool post…

20. Rakesh singh says: 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

21. sabuz85 says: 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.

22. qazi akhter junejo says: i need swapping in php with different methods.

23. sumesh says: hai miza,

loving friend,
sumesh

24. zigman says: thanks machi……..

25. PRINCE says: THANKS FOR THE NICE METHOD

26. eshae says: 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 …

27. Anwardeen says: 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

28. fikre says: i would like to join me to you!

29. recipesmela says: very good logic i am new learner of PHP and i am trying to understand how to swap

30. recipesmela says: 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”;
?>

31. Jess K says: great info here

32. foysal says: This is called programming. I thundered.

33. Algo says: 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

34. DAMAN says: Here is another simple one
a=b-a+(b=a) ;

35. baljinder says: 36. pappu says: thanks.used me in a gud way

37. navaneetha says: how can we swap 2 no.s by using only one equation?

38. tahir says: thanks a lot thanku

40. mohamed magdy says: awesome

41. martin says: Very nifty and well explained.

42. tsells says: You can do this in one statement – a = ((a + b) – (b=a))

43. MAHESH says: Excellent!!!!!

44. MAHESH says: Excellent!!!!

45. jayant says: really nice..

46. yatin tuli says: nice ….. solution

47. arpita says: Thank u very much….

48. sonu says: what happen if we take first number as smaller than second number

49. rokan says: nice…………. thank u………….

51. Jagan Salunkhe says: nice……….

52. bhanu says: good one …

53. Ajax Mint says: what about using extract for swapping?

extract(array(‘a’=>\$b, ‘b’=>\$a))

or

list(\$a, \$b) = array(\$b, \$a);

54. Kedir hassen says: I like this explanation

55. Kedir hassen says: 56. Ashwini says: how to swap values of three avriable if a->b->c->a

57. Rahul says: Thanx 2 make it clear.

58. vijay says: thank you!

59. qwerty says: big help thx

60. Amit Vaishnava says: 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

61. Rajeev Kumar Ranjan says: 62. kiranmayi says: good information.thnx!!!!

63. Mohsin says: goodiii……

64. Nirav says: good methods for beginner….thanks