4 Comments to “PHP Swap (Simple Swapping)”

  1. ruX

    Aug 27th, 2008

    Good idea :)
    AFIK, this construction needs more memory.

  2. miah

    Feb 23rd, 2009

    $a = ‘bar’;
    $b = ‘foo’;

    $a = $a ^ $b;
    $b = $a ^ $b;
    $a = $a ^ $b;

    echo $a . $b;

    // its faster and needs less memory ^^

  3. Blog SEO

    May 14th, 2009

    Nice trick, thanks :)

    miah, I like your trcik too ;)

    Thanks guys !

    Tiger

  4. David Hagler

    Dec 1st, 2009

    miah the xor trick only properly works on integers OR if string happen to be the same length, it will work, it’s best to avoid that trick unless you really need it.

    $a = “a”;
    $b = “gggggg”;

    $a = $a ^ $b;
    echo “$b “;
    $b = $a ^ $b;
    echo “$b “;
    $a = $a ^ $b;
    echo “$a $b “;

    // $a = ‘g’; $b = ‘a’;


Leave a Reply