Swap Values Without Temporary Varaibles In PHP

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.
CAPTCHA
8 + 0 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.