PHP Swap (Simple Swapping)


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 thoughts on “PHP Swap (Simple Swapping)

  1. David Hagler

    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