Say for instance I have ...
$var1 = \"ABC\"
$var2 = 123
and under certain conditions I want to sw
<?php
swap(50, 100);
function swap($a, $b)
{
$a = $a+$b;
$b = $a - $b;
$a = $a - $b;
echo "A:". $a;
echo "B:". $b;
}
?>
For numbers:
$a = $a+$b;
$b = $a-$b;
$a = $a-$b;
Working:
Let $a = 10, $b = 20.
$a = $a+$b (now, $a = 30, $b = 20)
$b = $a-$b (now, $a = 30, $b = 10)
$a = $a-$b (now, $a = 20, $b = 10 SWAPPED!)
If both variables are integers you can use mathematical approach:
$a = 7; $b = 10; $a = $a + $b; $b = $a - $b; $a = $a - $b;
Good blog post - http://booleandreams.wordpress.com/2008/07/30/how-to-swap-values-of-two-variables-without-using-a-third-variable/
It is also possible to use the old XOR trick ( However it works only correctly for integers, and it doesn't make code easier to read.. )
$a ^= $b ^= $a ^= $b;
There isn't a built-in function. Use swap3()
as mentioned below.
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.
swap2()
and swap4()
are always slower than the other ones because of the function call.swap1()
and swap3()
both performance speed are very similar, but most of the time swap3()
is slightly faster.swap1()
works only with numbers!Another way:
$a = $b + $a - ($b = $a);