So I’ve come accross these on PHP8 code from my office (simplified) :
[, $x] = $y;
I also saw the other way
[$x, ] = $y;
What would these do? If I do that in a sandbox and assign random values to $y beforehand, I don’t get anything for $x. I know that it is not badcode, as PHPStorm valids it.
I’ve tried searching for it, but every search engines including Stackoverflow will ignore commas or [], so I can’t get my answer.
2
Answers
It’s called array destructuring.
This is destructuring assignment. The variables in the array on the left are assigned from the corresponding elements of the array on the right. It’s equivalent to the old
list()
assignment.You can use commas with no variable before/after to indicate elements of the array that are skipped when assigning. Thus:
is equivalent to
and
is equivalent to
You wouldn’t usually use this syntax for assigning a single variable, it’s mostly useful for assigning multiple variables:
which is a shortcut for
There’s no need for the comma at the end of the list, but you might include them for the same reason you would include a comma in an array literal: it makes it easier to add additional elements (especially when you write them one per line).