Exchange values for two variables in PHP

Source: Internet
Author: User
Tags vars

Objective

Originally wanted to update PHP operation socket code, but because of the project reason is not in the mood, but over time will operate SMS Gateway, then naturally update the socket code, today is mainly how to use PHP Exchange two number.

List

First, use the PHP list data structure. On the code, and then parse the

[PHP]View PlainCopyprint?
    1. Function swap (&$a, &$b) {
    2. List ( $a, $b) = Array ($b, $a);
    3. }

List: Assigns the value of the array to the variable in the list, which is equivalent to assigning the value of $b to $ A and assigning a value of $ A to $b. Also, note the use of the & reference operator, which is a reference pass instead of a value pass.

XOR or operation

Three features of bitwise XOR:

    1. 0^1=1 0^0=0 = Therefore, 0 XOR or any number equal to any number itself
    2. 1^0=1 1^1=0 = Therefore, 1 xor or any number equals any number of counter
    3. Any number of different or yourself = put yourself 0

Well, don't say much, on the code

[PHP]View PlainCopyprint?
    1. Function Swap1 (&$a, &$b) {
    2. $a = $a ^ $b;
    3. $b = $a ^ $b;
    4. $a = $b ^ $a;
    5. }

Well, let's analyze why it's also possible to exchange.

$a = $a ^ $b;
$b = $a ^ $b = ($a ^ $b) ^ $b = $a ^ ($b ^ $b) = $a ^ 0, according to XOR or characteristic, 0 with any number XOR or equal to any number itself. The same can be deduced, $a = $b

Exchange values for two variables in PHP

Related Article

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.