Symmetric Array Destructuring in PHP
As of PHP 7.1, you can now use the shorthand array syntax to destructure your arrays for assignment. Previously you would have had to use a function like list, but now you can use the simple new array shorthand syntax.
As of PHP 7.1, you can now use the shorthand array syntax to destructure your arrays for assignment. Previously you would have had to use a function like list, but now you can use the simple new array shorthand syntax.
Let's look at some examples.
Basic Example
PHP
<?php
$names = [
'Frank Perez',
'Carmella Osman',
'Kristina Endo',
];
// New Shorthand Syntax
[$firstName, $lastName] = $names[0];
// Previous list() Syntax
list($firstName, $lastName) = $names[0];
Example Using Loops
PHP
<?php
$names = [
'Frank Perez',
'Carmella Osman',
'Kristina Endo',
];
$names = array_map(function($name) {
return explode(' ', $name);
}, $names);
foreach($names as [$firstName, $lastName]) {
echo $lastName . ', ' . $firstName . '<br>';
}