PHP: Swap Variables One Liner

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

  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 */

Comments 3

  1. Mark Simon wrote:

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

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

    Posted 22 Aug 2007 at 12:37 pm
  2. Aquaricat wrote:

    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?

    Posted 24 Oct 2008 at 5:06 pm
  3. miah wrote:

    $a = ‘bar’;
    $b = ‘foo’;

    $a = $a ^ $b;
    $b = $a ^ $b;
    $a = $a ^ $b;

    echo $a . $b;

    // it is faster and needs less memory

    Posted 23 Feb 2009 at 3:31 pm

Trackbacks & Pingbacks 2

  1. From Swapping Two Variables in One Line With PHP - Ninedays Blog - web development, photography, tutorials and adventure on 27 Dec 2007 at 5:09 pm

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

  2. From Swapping values in PHP | Ehsan Akhgari on 28 Jul 2008 at 8:10 pm

    [...] 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… [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *