Dismiss Notice
Welcome to Our Community
Wanting to join the rest of our members? Feel free to sign up today.

Tip : Swap values of two variables without using a third variable

Discussion in 'Programming' started by dman_2007, Apr 9, 2008.

  1. dman_2007

    dman_2007 Guest

    Here's a handy trick for you to swap values of two variables without using another variable :

      list($a, $b) = array($b, $a);
    The statement above will transfer value of variable $a to variable $b and vice versa.
  2. amit

    amit New Member Webmaster

    Here is one other method by which the values can be swaped in all the programing languages:

    This will also do the work.
  3. dman_2007

    dman_2007 Guest

    Another good method, a bit more involved but gets the job done. Here's another method using ^ (XOR) operator :

      $a = 10;
      $b = 20;
      echo '$a => ' , $a, ' $b => ', $b, '<br />';
      $a = $a ^ $b;
      $b = $a ^ $b;
      $a = $a ^ $b;
      echo '$a => ' , $a, ' $b => ', $b, '<br />';

Featured Resources (View All)

Share This Page