Workaround for PHP to exchange the value of 2 variables without a third variable

Source: Internet
Author: User

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

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.