PHP tutorial Variable swap _php tutorial

Source: Internet
Author: User
Attributed to Solomon W. Golomb; A method for swapping the values of both of the variables without using an intermediate variable (your can tell this dates From the Elder days, when variables were expensive!). Thanks to PHP ' s syntax It's also a one-liner.
$a ^= $b ^= $a ^= $b;
Okay, here's how it goes (yeah, like I need to make content-free posts just for the sake of an increment ...).
First, simplify the line; Noting that ^= was right-associative, which means that's on that line the rightmost operator was evaluated first, that's the Ignment operators also return the value of the they assign to their lvalue, and that Foo^=bar was shorthand for Foo=foo^bar:

Code:

$a ^= $b ^= $a ^= $b;
$a ^= ($b ^= ($a ^= $b));
$a = $a ^b;
$a ^= ($b ^= $a);
$a = $a ^ $b;
$b = $b ^ $a;
$a = $a ^ $b;

Recall what ^ does. Takes each pair of corresponding bits from their arguments (the internal binary representation of its arguments, which is), a nd xors them together to produce the corresponding bit of the result ("corresponding" means that the first bits of both AR Guments produce the first bit of the result, the second bits of both arguments produce the second bit of the result, and S O on. This was why, as Buzzly noted, it's important that both variables was the same size-demons probably start flying out of Y Our nose if one of them runs out of bits to XOR before the other. Does to a pair of variables, we have need to recap what it does to single bits



http://www.bkjia.com/PHPjc/445164.html www.bkjia.com true http://www.bkjia.com/PHPjc/445164.html techarticle attributed to Solomon W. Golomb; a method for swapping the values of the----variables without using an intermedia Te variable (you can tell this dates from the Elder days ...

  • 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.