Simple Switching of Variable Values

This just came to me, a rather nifty trick inspired by Python's tuples. I'm sure this is well known. But, I haven't written about anything useful in a while so I thought that I'd do something simple. Normally to switch the values of two variables one would do the following..

$a = 'a';
$b = 'b';
$c;

$c = $b;
$b = $a;
$a = $c;

var_dump($a); // output: b
var_dump($b); // output: a

This is pretty ugly, so lets simplify things a bit...


$a = 'a';
$b = 'b';

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

var_dump($a); // output: b
var_dump($b); // output: a

Cheers.

  • PHP
  • by Peter Goodman on Jul 27, 2007 @ 10:48am

Add a Comment