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.

$a = 1;
$b = 2;
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.

$a = 1;
$b = 2;
$c = 3;
$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.