RSS Feed

Peter Goodman's blog about PHP, Parsing Theory, C++, Functional Programming, Applications,

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.


Comments

There are no comments, but you look like you have something on your mind.


Comment