PHP does not exchange the value of 2 variables with a third variable _php instance

Source: Internet
Author: User
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/> ';

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.