DEV Community

Aju Chacko
Aju Chacko

Posted on

array deStructure

The short array syntax([]) is a language construct just like array(). This can be used to take variables out of an array. I mean to "destructure" the array into separate variables.

$array = ['a', 'b', 'c']; 

// Using the list syntax:
list($a, $b, $c) = $array;

// Or the shorthand syntax:
[$a, $b, $c] = $array;

// $a = 'a'
// $b = 'b'
// $c = 'c'

Suppose you only needed the last element of an array, the first two can be skipped by simply not providing a variable.

[, , $c] = $array;

// $c = 'c'

Also note that list will always start at index 0. Take for example the following array:

$array = [
    1 => 'a',
    2 => 'b',
    3 => 'c',
];

[$a, $b, $c] = $array;
echo $a;
// Notice: Undefined offset: 0

[ , $a, $b, $c] = $array;
echo $a;
// 'a'

The first variable pulled out with list would be null, because there's no element with index 0. This might seem like a shortcoming, but luckily there are more possibilities.

PHP 7.1 allows list to be used with arrays that have non-numerical keys. This opens a world of possibilities.

$array = [
    'a' => 1,
    'b' => 2,
    'c' => 3,
];

['c' => $c, 'a' => $a] = $array;

foreach ($array as ['id' => $id, 'name' => $name]) {
    // …
}

Top comments (0)