Forthcoming in PHP 7.1 is a concept that is officially called "Symmetric array destructuring". Holy computer science textbook, Batman.

Between me and you, I reckon you are more likely to hear this called "array destructuring", or simply just "destructuring".

It's a really useful concept. Essentially it allows us to quickly pluck elements out of an array, without having to define a bunch of individual variables:

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

[$foo, $bar, $baz] = $someArray;

echo $foo; // 'a'
echo $bar; // 'b'
echo $baz; // 'c'

Ok, this isn't going to change the world - but there are some important things to note here.

Firstly, whilst you (I?) never really saw it in real world code, this has been possible since PHP4 with the list function (technically not a function, but a PHP language construct):

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

list($foo, $bar, $baz) = $someArray;

echo $foo; // 'a'
echo $bar; // 'b'
echo $baz; // 'c'

The new syntax of being able to use the short hand array brackets - [] - definitely looks nicer.

And on the point of looks, this brings me on to the second important point here:

You will see this more and more if you do any modern JavaScript work. ES6 is full of destructuring assignments. My theory on this goes that whilst we didn't see the list($x,$y,$z) syntax that frequently, we can expect to see more of the short hand syntax as this concept cross polinates from JavaScript-land.

Thirdly, and perhaps where this becomes most useful, is in its use with foreach:

$people = [
  [ 'tim', 'jones', 32 ],
  [ 'bill', 'smith', 27 ],
];

foreach ($people as [$first, $last, $age]) {
  echo $first . ' ' . $last . ', aged: ' . $age . PHP_EOL;
}

In other words, for each person (row) in the array of $people, put the first array value in to the variable $first, the second array value in to $last, and the last array value in to $age.

Taking the first row, this means:

$first = 'tim';
$last = 'jones';
$age = 32;

Each of these array values now maps to a human readable piece of information.

Again, this is still possible with list in PHP4 onwards:

$people = [
  [ 'tim', 'jones', 32 ],
  [ 'bill', 'smith', 27 ],
];

foreach ($people as list($first, $last, $age)) {
  echo $first . ' ' . $last . ', aged: ' . $age . PHP_EOL;
}

For me, the short hand syntax is a definite readability improvement. As a result, I think this will be used more in the wild.

Sadly we can't do the JavaScript-esque object destructuring as of yet, but maybe it's one for the future?


Share This Episode

If you have found this video helpful, please consider sharing. I really appreciate it.


Episodes in this series

# Title Duration
1 Shorthand Destructuring 06:13
2 Nullable Types 06:37
3 Class Constant Visibility 03:15