Wednesday 15th August 2007

by Sajith M.R

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 Responses to “PHP Swap (Simple Swapping)”

  1. Sajith M.R says:

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

  2. yrhon says:

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

  3. David Hagler says:

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

  4. Blog SEO says:

    Nice trick, thanks :)

    miah, I like your trcik too ;)

    Thanks guys !

    Tiger

  5. miah says:

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

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

    echo $a . $b;

    // its faster and needs less memory ^^

  6. ruX says:

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

· · · ◊ ◊ ◊ · · ·

Leave a Reply

وظائف 2011 تحويل العملات برامج برنامج تسريع التحميل برنامج الفلاش برنامج محول الصوتيات عربي hotel 2011 زيادة رواتب العساكر 1431