I used to have a php interview question like this: Do not use the third variable to exchange the values of two variables. Generally, the third intermediate variable is used to realize the value exchange between the original two variables, but this question requires that the intermediate variable cannot be used, which is also a problem for beginners.
Several methods found on the Internet are summarized as follows:
Copy codeThe Code is as follows ://
The string version is implemented in combination with substr and strlen.
$ A = "";
$ B = "B ";
Echo '$ a: '. $ a.', $ B: '. $ B.' <br/> ';
$ A. = $ B;
$ B = substr ($ a, 0, (strlen ($ a)-strlen ($ B )));
$ A = substr ($ a, strlen ($ B ));
Echo '$ a: '. $ a.', $ B: '. $ B.' <br/> ';
Echo '----------------------- <br/> ';
// The string version is implemented using the str_replace Method
$ A = "";
$ B = "B ";
Echo '$ a: '. $ a.', $ B: '. $ B.' <br/> ';
$ A. = $ B;
$ B = str_replace ($ B, "", $ );
$ A = str_replace ($ B, "", $ );
Echo '$ a: '. $ a.', $ B: '. $ B.' <br/> ';
Echo '----------------------- <br/> ';
// The string version is implemented using the list method and array.
$ A = "";
$ B = "B ";
Echo '$ a: '. $ a.', $ B: '. $ B.' <br/> ';
List ($ B, $ a) = array ($ a, $ B );
Echo '$ a: '. $ a.', $ B: '. $ B.' <br/> ';
Echo '----------------------- <br/> ';
// Use exclusive or for both strings and numbers
$ A = 'a ';
$ B = 'B ';
Echo '$ a: '. $ a.', $ B: '. $ B.' <br/> ';
$ A = $ a ^ $ B;
$ B = $ B ^ $;
$ A = $ a ^ $ B;
Echo '$ a: '. $ a.', $ B: '. $ B.' <br/> ';
Echo '----------------------- <br/> ';
// Only applicable to numbers
$ A = 3;
$ B = 5;
Echo '$ a: '. $ a.', $ B: '. $ B.' <br/> ';
$ A = $ a + $ B;
$ B = $ a-$ B;
$ A = $ a-$ B;
Echo '$ a: '. $ a.', $ B: '. $ B.' <br/> ';