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;
}

But there is a shorter way using…


This content originally appeared on DEV Community and was authored by Thomas Haas

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;
}

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

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

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.


This content originally appeared on DEV Community and was authored by Thomas Haas


Print Share Comment Cite Upload Translate Updates
APA

Thomas Haas | Sciencx (2024-07-19T05:48:09+00:00) Swap variables in PHP using destructuring. Retrieved from https://www.scien.cx/2024/07/19/swap-variables-in-php-using-destructuring/

MLA
" » Swap variables in PHP using destructuring." Thomas Haas | Sciencx - Friday July 19, 2024, https://www.scien.cx/2024/07/19/swap-variables-in-php-using-destructuring/
HARVARD
Thomas Haas | Sciencx Friday July 19, 2024 » Swap variables in PHP using destructuring., viewed ,<https://www.scien.cx/2024/07/19/swap-variables-in-php-using-destructuring/>
VANCOUVER
Thomas Haas | Sciencx - » Swap variables in PHP using destructuring. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/07/19/swap-variables-in-php-using-destructuring/
CHICAGO
" » Swap variables in PHP using destructuring." Thomas Haas | Sciencx - Accessed . https://www.scien.cx/2024/07/19/swap-variables-in-php-using-destructuring/
IEEE
" » Swap variables in PHP using destructuring." Thomas Haas | Sciencx [Online]. Available: https://www.scien.cx/2024/07/19/swap-variables-in-php-using-destructuring/. [Accessed: ]
rf:citation
» Swap variables in PHP using destructuring | Thomas Haas | Sciencx | https://www.scien.cx/2024/07/19/swap-variables-in-php-using-destructuring/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.