DEV Community

Cover image for Swap variables in PHP using destructuring
Thomas Haas
Thomas Haas

Posted on

Swap variables in PHP using destructuring

Swapping variables is a common task, teached and often implemented using a temporary variable like this:

function swap(&$left, &$right): void
{
    $tmp = $left;
    $left = $right;
    $right = $tmp;
}
Enter fullscreen mode Exit fullscreen mode

But there is a shorter way using destructuring (since php 7.1!):

function swap(&$left, &$right): void
{
    [$left, $right] = [$right, $left];
}
Enter fullscreen mode Exit fullscreen mode

Maybe the code looks a bit strange and I haven't analysed it for performance issues, but it helps to understand destructuring.

Btw., that's not a php-only feature, feel free to test it e.g. in javascript.

Top comments (0)