DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 968,547 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
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)

πŸ‘‹ Hey, my name is Noah and I’m the one who set up this ad. My job is to get you to join DEV, so if you fancy doing me a favor, I’d love for you to create an account.

If you found DEV from searching around, here are a couple of our most popular articles on DEV: