Search code examples
phparraysdefinition

PHP empty array definition with starting or ending comma


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.


Solution

  • $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.