Tuesday 30 September 2014

Multiple assignment and variable swapping

It is generally known that PHP doesn't natively support multiple assignment or variable swapping. Multiple assignment can be done by using multiple assignment statements. Variable swapping on the other hand can be done for integers using the XOR trick:

10; $y 20; $x ^= $y ^= $x ^= $y;
$x ' | ' $y// outputs: 20 | 10

But as said, this only works for integers. And look at it, it's hideous.

But there is a way that is quite elegant and php-ish. Since 5.4 it has become even better with the short array syntax:

10; $y 20;
$y$x) = [$x$y];
$x ' | ' $y// outputs: 20 | 10

I wonder why I didn't think of this earlier!

This might even get better starting PHP 7 or later. Good things!

Happy coding, guys :)