Coding Triumph

Helpful code snippets & tutorials

How to destructure an array in PHP

Array destructuring is an assignment expression that makes it possible to unpack values from arrays into separate variables. In PHP, there are two language constructs we can use to unpack an array: list and the array shorthand syntax[].

1. Destructuring an indexed array:

Probably the indexed array is the simplest to destructure and supported since PHP 4. This is how you can do it:

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

# using the list syntax
list($a, $b, $c, $d, $e) = $array;

# using the array shorthand syntax
[$a, $b, $c, $d, $e] = $array;

# $a == 'a', $b == 'b', $c == 'c', $d == 'd', $e == 'e'

2. Destructuring an associative array:

As of PHP 7.1, it’s possible to destructure an associative array using list and the array symbol [] although the syntax is a bit different. Here is an example:

$array = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5];

# using the list syntax
list('a' => $a, 'b' => $b, 'c' => $c, 'd' => $d, 'e' => $e) = $array;

# using the [] shorthand
['a' => $a, 'b' => $b, 'c' => $c, 'd' => $d, 'e' => $e] = $array;

# $a == 1, $b == 2, $c == 3, $d == 4, $e == 5

Whether you prefer list or its shorthand [] counterpart is up to you. Personally, I prefer using []. What about you?

If you like this post, please share
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments