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

This site runs on the Thesis WordPress Theme

Thesis Theme thumbnail

If you're someone who doesn't understand a lot of PHP, HTML, or CSS, Thesis will give you a ton of functionality without having to alter any code. For the advanced, Thesis has incredible customization possibilities via extensive hooks and filters. And with so many design options, you can use the template over and over and never have it look like the same site.

If you're more familiar with how websites work, you can use the fantastic Thesis User's Guide and world-class support forums to make more professional customizations than you ever thought possible. The theme is not only highly customizable, but it allows me to build sites with a much more targeted focus on monetization than ever before. You can find out more about Thesis below:

{ 8 comments… read them below or add one }

Matt June 28, 2008 at 4:33 am
function swap (&$x, &$y) {
  $x ^= $y ^= $x ^= $y;
}

This means you don’t have to do anything like:

list($x, $y) = swap($x, $y);

You can just do:

swap($x, $y);

Reply

Aquaricat October 24, 2008 at 2:40 pm

The trouble with `list($x,$y) = array($y,$x);` is that it completely defeats the purpose of doing a bitwise swap – the usefulness of a bitwise swap is that it saves memory. Rather than initializing an extra variable, it swaps the two values in place. These days, that’s not all that important, but in environments where memory comes at a premium, every little bit helps.

Now, consider what happens when you use the list($x,$y) = array($y,$x); method – you’re creating an array, which at best takes twice as much space as a single temp var, but you’re also executing not just one, but two additional methods which are going to absorb memory. Those in turn may contain temporary variables, which are going to absorb even more memory.

In short, you’ve gone from a method that requires no extra memory, to a method that could arguably consume an unlimited amount extra – obviously that’s not going to happen with a simple two variable swap, but the potential is there. That said, you’re adding a LOT of overhead with list($x,$y) = array($y,$x);.

Reply

Levi February 21, 2012 at 11:04 pm

“In short, you’ve gone from a method that requires no extra memory, to a method that could arguably consume an unlimited amount extra”

Actually, PHP uses copy-on-write and reference counting.

In the following, $x and $y refer to the same location in memory. It’s only when you modify a value in the array that php actually makes a second copy (If it didn’t the following would use 1gb of memory instead of 1mb)

Reply

Levi February 21, 2012 at 11:05 pm

Edit: it stripped out the PHP code:

echo memorygetusage().”\n”;
$x = arrayfill(0, 1024, strrepeat(‘ ‘, 1024*1024));
each($x);
echo memorygetusage().”\n”;
$y = $x;
echo memorygetusage().”\n”;
list($x,$y) = array($y,$x);
echo memorygetusage().”\n”;

Reply

Terri Ann
Twitter:
October 24, 2008 at 7:50 pm

@aquaricat This post was mostly about exploring different approaches and different ways to accomplish the same task. You made an excellent point and I greatly appreciate you contributing your knowledge! I didn’t really put as much thought into memory usage as it’s not my area of expertise.

Reply

Susenjit Chanda August 6, 2009 at 9:06 am

Your one line swap is really a good code. Though memory usage is not so much important these days but the approach is effective if you wanna do this in a single line. Thanx for the code.

Reply

Derrick Coetzee January 15, 2012 at 7:49 am

XOR swap is almost never a good idea on modern processors – swapping using ordinary moves is superior, and any arbitrarily large object can be swapped one word at a time using only one spare word of memory, which is no big deal. See Wikipedia: XOR swap algorithm – Reasons for avoidance in practice

  • Edited by Admin 1/23/2012 to fix link

Reply

Terri Ann
Twitter:
January 23, 2012 at 12:13 pm

It’s funny you mention that Derrick because I thought I was pretty clear in the post that while you could do it that way I would have a hard time coming up with a case where you would WANT to do it that way. Usually this is just a trick you want to look over before walking into an interview! Thanks for the link to the Wiki article – it’s a great read.

Reply

Leave a Comment

Previous post:

Next post: