Home > Backend Development > PHP Tutorial > Swap variables in PHP using destructuring

Swap variables in PHP using destructuring

WBOY
Release: 2024-07-19 15:25:37
Original
1004 people have browsed it

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;
}
Copy after login

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

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

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.

The above is the detailed content of Swap variables in PHP using destructuring. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template