# Destructuring 7.1
You can destructure arrays to pull out several elements into separate variables:
$array = [1, 2, 3];
// Using the list syntax:
list($a, $b, $c) = $array;
// Or the shorthand syntax:
[$a, $b, $c] = $array;
You can skip elements:
[, , $c] = $array;
As well as destructure based on keys:
$array = [
'a' => 1,
'b' => 2,
'c' => 3,
];
['c' => $c, 'a' => $a] = $array;
# Rest and Spread Operators 5.6
Arrays can be spread into functions:
$array = [1, 2];
function foo(int $a, int $b) { }
foo(...$array);
Functions can automatically collect the rest of the variables using the same operator:
function foo($first, ...$other) { }
foo('a', 'b', 'c', 'd', …);
Rest parameters can even be type hinted:
function foo($first, string ...$other) { }
foo('a', 'b', 'c', 'd', …);
7.4 Arrays with numerical keys can also be spread into a new array:
$a = [1, 2];
$b = [3, 4];
$result = [...$a, ...$b];
8.1 You can also spread arrays with textual keys starting from PHP 8.1
from Hacker News https://ift.tt/3fi1jqv
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.