yes i love technology

PHP: Swap Variables One Liner

March 29th, 2007 by Pete

Here's a nifty one liner in PHP which let's you swap 2 variables values.

PHP:
  1. list($a,$b) = array($b,$a);

Much like the PHP XOR swap there's no real reason this is any better than using a temporary variable, but you might be able to impress chicks with it or something.

/* Pete Graham */

Posted in Tech, php, programming |

4 Responses

  1. Mark Simon Says:

    … except that it makes it easier to write another one-liner like this:

    if(whatever) list($a,$b)=array($b,a);

  2. Swapping Two Variables in One Line With PHP - Ninedays Blog - web development, photography, tutorials and adventure Says:

    […] And then one day while perusing the internet I found an even easier solution on Optimus Pete - PHP Swap Variables One Liner. […]

  3. Swapping values in PHP | Ehsan Akhgari Says:

    […] It’s always a good thing to search for something cool that you’ve found before blogging it, to make sure that others have not already done the same!    It even helped me see a PHP trick that should be familiar to seasoned C/C++ programmers… […]

  4. Aquaricat Says:

    Doesn’t this just introduce the overhead of creating a temporary array? If the value of XOR swapping is that it saves memory, wouldn’t doing this just waste double the memory of making a single temporary variable?

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.