Swapping Two Variables in One Line With PHP
When talking to a friend of mine, Tim, one day he was challenging my programmer knowledge. He of course pulled out the all time "Swap 2 variables in 1 line without using a temporary variable."
Of course I didn't know the answer. There's rarely a need for this application with what I do, for me it appears to be more of a trivia item or an interview question.
Either way I was sitting here watching trashy VH1 reality TV shows and surfing MySpace when I realized I had not learned anything today.
So I Googled and learned about PHP: bitwise operators and that this one line would swap two variables without a temporary variable.
The One Line Swap
PHP
$x ^= $y ^= $x ^= $y;
I wrote a quick function for something like this too!
PHP
function swap($x, $y) {
$x ^= $y ^= $x ^= $y;
return array($x,$y);
}
Once you get to the function you are using more than one line and possibly taking more processing power but it's a good library piece.
My Test Script
The whole script I was testing and playing with looked like this:
PHP
<?php
function swap($x, $y) {
$x ^= $y ^= $x ^= $y;
return array($x,$y);
}
$x = 6;
$y = 2;
echo 'y: ' . $y . ' x: ' . $x;
// Prints 'y: 2 x: 6
// Using a function
list($x, $y) = swap($x, $y);
echo 'y: ' . $y . ' x: ' . $x;
// Prints 'y: 6 x: 2
// Using inline operators
$x ^= $y ^= $x ^= $y;
echo 'y: ' . $y . ' x: ' . $x;
// Prints 'y: 2 x: 6
?>
Good stuff huh?
Update 12/27/2007 new
Easier 1 Line 2 var Swap
And then one day while perusing the internet I found an even easier solution on Optimus Pete - PHP Swap Variables One Liner.
PHP
<?php
list($x,$y) = array($y,$x);
?>
Way easier than my function, though live and learn. At least now through exploration I know more about PHP's XOR swapping.
Additional Resources
the newest discoveries, stories and shared tips!Come on, all the cool kids are doing it ;)



This means you don't have to do anything like:
You can just do: