12/26/2012

PHP swap two variables

Some ways for swapping two variables

1. temporary variable
    $a = 100;
    $b=200;
    $tmp = $a;
    $a = $b;
    $b = $tmp;


2. list
    $a = 100;
    $b=200;
    list($b,$a) = array($a,$b);

3. XOR
    $a = 100;
    $b=200;

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

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


Note
  1.  The ways 1 and 2 can be used for any variable, including array, object, etc.
  2. The way 3 can not be used on array, object.


   

No comments:

Post a Comment