"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Swap variables in PHP using destructuring

Swap variables in PHP using destructuring

Published on 2024-08-20
Browse:167

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 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.

Release Statement This article is reproduced at: https://dev.to/tahomash/swap-variables-in-php-using-destructuring-4n64?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3