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.'
';
http://www.bkjia.com/PHPjc/327076.htmlwww.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,...