Swapping two variables in PHP

In my last post at some point in the code I had to do a variable swap (to assign the value of the second variable to the first and vice-versa). To do this I used a third temporary variable to hold the content of the first variable so it’s value won’t be lost.

$temp = $a;
$a = $b;
$b = $temp;

It was pointed out to me I could have done the variable interchange differently so here you are a few of the methods I could think of.

The arithmetical operations method (subtractions and additions) :

$a = $a + $b; 
$b = $a - $b; 
$a = $a - $b;

or shorther:

$a = $a + $b - ( $b = $a );

Another arithmetical operations method (multiplying and dividing):

$a = $a*$b;
$b = $a / $b;
$a = $a / $b;

There is the XOR method which is a little more difficult to understand but once you get it you love it:

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

or shorter:

$a = $a ^ $b ^ ( $b = $a );

And there is also a PHP specific method:

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

The first method, though a bit costly (it uses a third variable), works with all types of variables and is the easiest to read and understand which under normal circumstances (not being pressed by memory or CPU operations limitations) makes it a definite winner.

The second method method only works with numeric values and written in one line is more difficult to read and understand.

The third method only works with numeric values too but also both of the variables must be different then 0 (zero).

The fourth method works with integers only but has the advantage of being the fastest and the cheapest (resource wise). It has the disadvantage of being the hardest to read and understand though.

The last one is the most expensive and also PHP specific. It’s harsh and excessive but I thought it was worth mentioning.

1 comment to Swapping two variables in PHP

Leave a Reply

  

  

  

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Categories

Archives

Calendar

June 2017
M T W T F S S
« Jul    
 1234
567891011
12131415161718
19202122232425
2627282930