PHP solution for exchanging the values of two variables without using a third variable

  • 2020-06-03 06:05:21
  • OfStack

I've done an php interview before: exchange the values of two variables without using the third variable. In general, the third intermediate variable is used to exchange the value of the original two variables, but this problem requires that you cannot use the intermediate variable, which is also a problem for beginners. Several methods found on the Internet are summarized as follows:

// String version   Use a combination of substr . strlen Two method implementations 
$a="a";
$b="b";
echo ' Exchange before  $a:'.$a.',$b:'.$b.'<br />';
$a.=$b;
$b=substr($a,0,(strlen($a)-strlen($b)));
$a=substr($a, strlen($b));
echo ' After exchanging $a:'.$a.',$b:'.$b.'<br />';

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

// String version   use str_replace Method implementation 
$a="a";
$b="b";
echo ' Exchange before  $a:'.$a.',$b:'.$b.'<br />';
$a.=$b;
$b=str_replace($b, "", $a);
$a=str_replace($b, "", $a);
echo ' After exchanging $a:'.$a.',$b:'.$b.'<br />';

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

// String version   Use a combination of list Methods and array implementation 
$a="a";
$b="b";
echo ' Exchange before  $a:'.$a.',$b:'.$b.'<br />';
list($b,$a)=array($a,$b);
echo ' After exchanging $a:'.$a.',$b:'.$b.'<br />';

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

// Both strings and Numbers apply   Use an xor operation 
$a='a';
$b='b';
echo ' Exchange before  $a:'.$a.',$b:'.$b.'<br />';
$a=$a^$b;
$b=$b^$a;
$a=$a^$b;
echo ' After exchanging $a:'.$a.',$b:'.$b.'<br />';

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

// This applies only to Numbers 
$a=3;
$b=5;
echo ' Exchange before  $a:'.$a.',$b:'.$b.'<br />';
$a=$a+$b;
$b=$a-$b;
$a=$a-$b;
echo ' After exchanging $a:'.$a.',$b:'.$b.'<br />';


Related articles: