Is there a PHP function for swapping the values of two variables?
There's no function I know of, but there is a one-liner courtesy of Pete Graham:
list($a,$b) = array($b,$a);
not sure whether I like this from a maintenance perspective, though, as it's not really intuitive to understand.
Also, as @Paul Dixon points out, it is not very efficient, and is costlier than using a temporary variable. Possibly of note in a very big loop.
However, a situation where this is necessary smells a bit wrong to me, anyway. If you want to discuss it: What do you need this for?
TL;DR
There isn't a built-in function. Use swap3()
as mentioned below.
Summary
As many mentioned, there are multiple ways to do this, most noticable are these 4 methods:
function swap1(&$x, &$y) {
// Warning: works correctly with numbers ONLY!
$x ^= $y ^= $x ^= $y;
}
function swap2(&$x, &$y) {
list($x,$y) = array($y, $x);
}
function swap3(&$x, &$y) {
$tmp=$x;
$x=$y;
$y=$tmp;
}
function swap4(&$x, &$y) {
extract(array('x' => $y, 'y' => $x));
}
I tested the 4 methods under a for-loop of 1000 iterations, to find the fastest of them:
swap1()
= scored approximate average of 0.19 seconds.swap2()
= scored approximate average of 0.42 seconds.swap3()
= scored approximate average of 0.16 seconds. Winner!swap4()
= scored approximate average of 0.73 seconds.
And for readability, I find swap3()
is better than the other functions.
Note
swap2()
andswap4()
are always slower than the other ones because of the function call.swap1()
andswap3()
both performance speed are very similar, but most of the timeswap3()
is slightly faster.- Warning:
swap1()
works only with numbers!