PHP Swap (Simple Swapping)

swap.thumbnail

PHP Simple Swap >>

Hello programmers,

You know list function in php and array function. Just
type like below for swapping two variables $a and $b.

list($b,$a) = array($a,$b);

The above code is equivalent to:

$temp = $a;

$a = $b ;

$b= $temp;

Here we shorten the three line of code into a single line.

6 Comments

6 Responses to “PHP Swap (Simple Swapping)”

  1. ruX August 27, 2008 at 12:55 am #

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

  2. miah February 23, 2009 at 10:00 pm #

    $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 14, 2009 at 7:54 pm #

    Nice trick, thanks :)

    miah, I like your trcik too ;)

    Thanks guys !

    Tiger

  4. David Hagler December 1, 2009 at 10:04 pm #

    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’;

  5. yrhon July 29, 2010 at 1:11 pm #

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

    • Sajith M.R July 31, 2010 at 3:26 pm #

      Yes good , but it won’t work for all types of object swapping, say an array swap . Only for integers

Leave a Reply

More in php (99 of 108 articles)


In normal desktop applications , we use exception handling everywhere in our code. But in server side script such ...