Previously done a PHP interview question is this: do not use the third variable to exchange the value of two variables. Generally is the use of the Third intermediate variable to achieve the original two variable value exchange, but this problem requires the use of intermediate variables, which for beginners is also a difficult problem.
Several methods found on the Internet are summarized as follows:
Copy Code code as follows:
//
string versions are implemented in combination with Substr,strlen two methods
$a = "a";
$b = "B";
Echo ' $a before Exchange: '. $a. ', $b: '. $b. ' <br/> ';
$a. = $b;
$b =substr ($a, 0, (strlen ($a)-strlen ($b));
$a =substr ($a, strlen ($b));
Echo ' Exchange after $a: '. $a. ', $b: '. $b. ' <br/> ';
Echo '-----------------------<br/> ';
String versions are implemented using the Str_replace method
$a = "a";
$b = "B";
Echo ' $a before Exchange: '. $a. ', $b: '. $b. ' <br/> ';
$a. = $b;
$b =str_replace ($b, "", $a);
$a =str_replace ($b, "", $a);
Echo ' Exchange after $a: '. $a. ', $b: '. $b. ' <br/> ';
Echo '-----------------------<br/> ';
String version combined with list method and array implementation
$a = "a";
$b = "B";
Echo ' $a before Exchange: '. $a. ', $b: '. $b. ' <br/> ';
List ($b, $a) =array ($a, $b);
Echo ' Exchange after $a: '. $a. ', $b: '. $b. ' <br/> ';
Echo '-----------------------<br/> ';
Both strings and numbers apply with XOR or operation
$a = ' a ';
$b = ' B ';
Echo ' $a before Exchange: '. $a. ', $b: '. $b. ' <br/> ';
$a = $a ^ $b;
$b = $b ^ $a;
$a = $a ^ $b;
Echo ' Exchange after $a: '. $a. ', $b: '. $b. ' <br/> ';
Echo '-----------------------<br/> ';
Applies only to numbers
$a = 3;
$b = 5;
Echo ' $a before Exchange: '. $a. ', $b: '. $b. ' <br/> ';
$a = $a + $b;
$b = $a-$b;
$a = $a-$b;
Echo ' Exchange after $a: '. $a. ', $b: '. $b. ' <br/> ';