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

Information and Links

Join the fray by commenting, tracking what others have to say, or linking to it from your blog.


Similar Entries
MySQL Queries Made Easy With PHP Functions Library
Every web developer has a library of code that they reference frequently, if not constantly. I'm sharing with you one of my most useful snippets my MySQL helper class that helps me organize my queries and easily reference commonly used functions.
Multiple Select Drop Down Menu in PHP
It's very easy to take what we did back in January for reusable PHP drop down menu code and make it work for multi value select elements.
I got Written up Twice Today…Blog Style!
I got written up in two blogs today. How cool is that?!?!
Multiple and Dynamic Variable Assignment in PHP
Assigning variables is a core part of any PHP script but there's many different ways to work with assignments. Assign multiple variables on one line, dynamic variable and references can change the way you think about using variables.
Path and Directory Function in PHP
Some great handy PHP functions for dissecting file paths and getting full paths for how they relate to the file you are in. Never again shall we explode or split a string on / or .!
Next Post
Search Query for 404 Error Pages Wordpress
Previous Post
Feed Image Wordpress Plugin

Write a Comment

Take a moment to comment and tell us what you think. Some basic HTML is allowed for formatting.

Reader Comments

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);

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);.

@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.