Home  >  Article  >  Backend Development  >  Swap the values ​​of two variables without using a new variable

Swap the values ​​of two variables without using a new variable

WBOY
WBOYOriginal
2016-08-08 09:27:391052browse

I often encounter this question during interviews, so I studied it specifically, as the question

$a = 1;

$b = 2;

Method 1:

$a ^= $b;$b ^= $a; $a ^= $b;

Method 2:

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

Method 3: (If the variable is an integer)

$a=$a+$b; $b=$a-$b; $a=$a-$b;

The above introduces how to exchange the values ​​​​of two variables without new variables, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn