Here's a nifty one liner in PHP which let's you swap 2 variables values.
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
… 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 ¶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 ¶$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
[...] And then one day while perusing the internet I found an even easier solution on Optimus Pete – PHP Swap Variables One Liner. [...]
[...] 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