"PHP does not need a third variable to exchange the value of two variables" This problem has been seen many times, it seems that the interview does like to test this problem. Today, for this topic, I have summed up several methods, may not be complete, we have to complement each other.
Method One: Using string interception
<?php
$a = "Fsdfds";
$b = "Xiaorui";
$a = $a. $b;
$b = substr ($a, 0,strlen ($a)-strlen ($b));
$a = substr ($a, strlen ($b));
echo $a. " -". $b;
?>
Method Two: Use List ()
<?php
$a = "PHP";
$b = "Java";
The list () is not a function, it is a language structure that assigns values from an array to some variables
List ($a, $b) = Array ($b, $a);
echo $a. '---' $b; Java---PHP
?>
Method Three: Using array segmentation
<?php
$a = "Fsdfds";
$b = "Xiaorui";
$b = $a. " #$ ". $b;
$b = Explode ("#$", $b);
$a = $b [1];
$b = $b [0];
echo $a. " -". $b;
?>
Note: This method can also be used to exchange the value of two variables, but this method is heard to be not very standard, because some people say that the array $b is also a new variable (I am a bit disagree, see how to understand).
Method Four: Use XOR or operation
<?php
$a = "Fsdfds";
$b = "Xiaorui";
$a = $a ^ $b;
$b = $b ^ $a;
$a = $a ^ $b;
echo $a. " -". $b;
?>
Description: This method is online to see, I carefully tried, found that this incredibly is a bug. The secondary method can only exchange two string-type variables with the same character, otherwise the result is incorrect.
Find some ways to do it online
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/> ';