Swap Values Without Temporary Varaibles In PHP

28th October 2008 - 1 minute read time

I have talked about swapping values without a temporary third variable before, but there is another way to do this which doesn't make the code unreadable. This is by using the list() function in the following way.

  1. $a = 1;
  2. $b = 2;
  3. list($a,$b) = array($b,$a);

This swaps the two values over. The good thing about this function is that you can swap any number of values over without the need to create lots of confusing temporary variables or using complicated looking bitwise operators. Take 4 variables.

  1. $a = 1;
  2. $b = 2;
  3. $c = 3;
  4. $d = 4;

These values can be entirely swapped using the list() function in the following way.

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

It should be noted that this code isn't faster than using temporary variables and so should only really be used to make it clear what is going on.

Add new comment

The content of this field is kept private and will not be shown publicly.