PHP empty array definition with starting or ending comma

62 views Asked by At

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

There are 2 answers

1
ezw On BEST ANSWER
$array = [10, 20, 30];

[$x, ] = $array;

echo $x;  // Output: 10

[, $x] = $array;

echo $x;  // Output: 20

[2 => $x] = $array;

echo $x;  // Output: 30

It's called array destructuring.

4
Barmar On

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:

[, $x] = $y;

is equivalent to

$x = $y[1];

and

[$x, ] = $y;

is equivalent to

$x = $y[0];

You wouldn't usually use this syntax for assigning a single variable, it's mostly useful for assigning multiple variables:

[$a, $b, , $c] = $y;

which is a shortcut for

$a = $y[0];
$b = $y[1];
$c = $y[3];

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