One of the previous PHP interview questions was this: do not use the third variable to implement the value of exchanging two variables. In general, the Third intermediate variable is used to realize the value exchange of the original two variables, but this problem does not require the use of intermediate variables, which for beginners is a problem. Some of the methods found online are summarized as follows:
Copy CodeThe code is as follows:
//
The string version is implemented in conjunction with Substr,strlen two methods
$a = "a";
$b = "B";
Echo ' Before Exchange $a: '. $a. ', $b: '. $b. ' <br/> ';
$a. = $b;
$b =substr ($a, 0, (strlen ($a)-strlen ($b)));
$a =substr ($a, strlen ($b));
Echo ' Swap $ A: '. $a. ', $b: '. $b. ' <br/> ';
Echo '-----------------------<br/> ';
The string version is implemented using the Str_replace method
$a = "a";
$b = "B";
Echo ' Before Exchange $a: '. $a. ', $b: '. $b. ' <br/> ';
$a. = $b;
$b =str_replace ($b, "", $a);
$a =str_replace ($b, "", $a);
Echo ' Swap $ A: '. $a. ', $b: '. $b. ' <br/> ';
Echo '-----------------------<br/> ';
String versions use the list method with the array implementation
$a = "a";
$b = "B";
Echo ' Before Exchange $a: '. $a. ', $b: '. $b. ' <br/> ';
List ($b, $a) =array ($a, $b);
Echo ' Swap $ A: '. $a. ', $b: '. $b. ' <br/> ';
Echo '-----------------------<br/> ';
Both strings and numbers are suitable for using XOR or arithmetic
$a = ' a ';
$b = ' B ';
Echo ' Before Exchange $a: '. $a. ', $b: '. $b. ' <br/> ';
$a = $a ^ $b;
$b = $b ^ $a;
$a = $a ^ $b;
Echo ' Swap $ A: '. $a. ', $b: '. $b. ' <br/> ';
Echo '-----------------------<br/> ';
Applies only to Digital
$a = 3;
$b = 5;
Echo ' Before Exchange $a: '. $a. ', $b: '. $b. ' <br/> ';
$a = $a + $b;
$b = $a-$b;
$a = $a-$b;
Echo ' Swap $ A: '. $a. ', $b: '. $b. ' <br/> ';
Workaround for PHP to exchange the value of 2 variables without a third variable