I want to perform Destructuring in php just like in javascript code below:
[a, b, ...rest] = [10, 20, 30, 40, 50];
console.log(a,b,rest);
Output:
10 20 [ 30, 40, 50 ]
How can I preform that operation in php?
My php code is:
<?php
$array = [10, 20, 30, 40, 50];
// Using the list syntax:
//list($a, $b, $c[]) = $array;
// Or the shorthand syntax:
[$a, $b, $c[]] = $array;
echo "$a<br>$b<br>";
print_r ($c);
?>
Which prints:
10
20
Array ( [0] => 30 )
But I want "[ 30, 40, 50 ]" in $c
5
Answers
Unfortunately that isn’t possible with the spread parameter in PHP.
However if you would like to achieve your result you could also first destructerize your wanted values. And then use the
array_slice()
function for your$c
parameter like the following:Results into:
PHP does not implement spread operator in the left side of assignments. As an alternative, you can extract elements from the head of the array:
… or:
The array keeps on loading, so use
instead.
gives
PHP will not allow you to unpack a dynamic amount of data using the left side of the assignment, so for a fully dynamic one-liner, use the right side of the assignment to prepare/group the data after the first two elements.
Code: (Demo)
The above snippet will work as intended for input arrays which have at least 2 element.
you can’t destructure array directly like
There is no direct method to Destructuring an array
You can use
array_slice()
So how you can destructure an array.