PHP not third variable swapping values of 2 variables

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

      Done before a PHP interview question is this: do not use third variables to achieve swapping values of two variables. Usually by the third intermediate variables to achieve the original values of two variables of exchange, but the problem is the requirements can not use the intermediate variables for beginners, this is also a problem. Several methods to find online are summarized as follows:

//String version of the combined use of substr, implementation of strlen two method
$a="a";
$b="b";
echo 'Before the exchange$a:'.$a.',$b:'.$b.'<br />';
$a.=$b;
$b=substr($a,0,(strlen($a)-strlen($b)));
$a=substr($a, strlen($b));
echo 'After the exchange of$a:'.$a.',$b:'.$b.'<br />';
 
echo '-----------------------<br/>';
 
//String version using the str_replace method
$a="a";
$b="b";
echo 'Before the exchange$a:'.$a.',$b:'.$b.'<br />';
$a.=$b;
$b=str_replace($b, "", $a);
$a=str_replace($b, "", $a);
echo 'After the exchange of$a:'.$a.',$b:'.$b.'<br />';
 
echo '-----------------------<br/>';
 
//String version using list methods and array implementation
$a="a";
$b="b";
echo 'Before the exchange$a:'.$a.',$b:'.$b.'<br />';
list($b,$a)=array($a,$b);
echo 'After the exchange of$a:'.$a.',$b:'.$b.'<br />';
 
echo '-----------------------<br/>';
 
//Strings and numbers are suitable for the use of XOR operation
$a='a';
$b='b';
echo 'Before the exchange$a:'.$a.',$b:'.$b.'<br />';
$a=$a^$b;
$b=$b^$a;
$a=$a^$b;
echo 'After the exchange of$a:'.$a.',$b:'.$b.'<br />';
 
echo '-----------------------<br/>';
 
//Only applicable to digital
$a=3;
$b=5;
echo 'Before the exchange$a:'.$a.',$b:'.$b.'<br />';
$a=$a+$b;
$b=$a-$b;
$a=$a-$b;
echo 'After the exchange of$a:'.$a.',$b:'.$b.'<br />';


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Amy at October 27, 2013 - 11:54 PM