PHP does not use a third variable to exchange the values of two variables

Source: Internet
Author: User

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/> ';

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.