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:

<?php
$x 
10; $y 20; $x ^= $y ^= $x ^= $y;
echo 
$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:

<?php
$x 
10; $y 20;
list(
$y$x) = [$x$y];
echo 
$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 :)