Home > Backend Development > PHP Tutorial > PHP solution to exchange the values ​​​​of two variables without using a third variable_PHP tutorial

PHP solution to exchange the values ​​​​of two variables without using a third variable_PHP tutorial

WBOY
Release: 2016-07-21 15:10:39
Original
784 people have browsed it

A PHP interview question I did before was this: exchange the values ​​of two variables without using a third variable. Generally, a third intermediate variable is used to exchange the values ​​of the original two variables, but this question requires that the intermediate variable cannot be used, which is also a difficult problem for beginners. The several methods found on the Internet are summarized as follows:

Copy the code The code is as follows:

//The string version uses substr and strlen methods to implement
$a="a";
$b="b";
echo 'before exchange $a:'.$a.',$b:'.$b.'
';
$a.=$b;
$b=substr($a,0, (strlen($a)-strlen($b)));
$a=substr($a, strlen($b));
echo '$a after exchange:'.$a.', $b:'.$b.'
';

echo '-----------------------< br/>';

//The string version is implemented using the str_replace method
$a="a";
$b="b";
echo '$a before exchange :'.$a.',$b:'.$b.'
';
$a.=$b;
$b=str_replace($b, "", $ a);
$a=str_replace($b, "", $a);
echo 'After exchange $a:'.$a.',$b:'.$b.'
';

echo '-----------------------
';

//The string version uses the list method and array to implement
$a="a";
$b="b";
echo '$a before exchange:'.$a.',$ b:'.$b.'
';
list($b,$a)=array($a,$b);
echo 'After exchange $a:'.$ a.',$b:'.$b.'
';

echo '--------------------- --
';

//XOR operation is applicable to both strings and numbers
$a='a';
$b='b';
echo '$a before exchange:'.$a.',$b:'.$b.'
';
$a=$a^$b;
$b= $b^$a;
$a=$a^$b;
echo 'After exchange $a:'.$a.',$b:'.$b.'
';

echo '-----------------------
';

//only Applicable to numbers
$a=3;
$b=5;
echo 'before exchange $a:'.$a.',$b:'.$b.'
$a=$a+$b;
$b=$a-$b;
$a=$a-$b;
echo '$a after exchange:'. $a.',$b:'.$b.'
';

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/327076.htmlTechArticleI once did a PHP interview question like this: Exchange the values ​​​​of two variables without using a third variable . Generally, the value exchange of the original two variables is achieved with the help of a third intermediate variable,...
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template