In this post, I will show you how you can use the new Symmetric array destructuring feature of PHP7.1 version. In the previous version of PHP, we used list method to destructure arrays for assignments.
The shorthand array syntax ([])
may now be used to destructure arrays for assignments (Including within foreach), as an alternative to the existing list()
syntax, which is still supported.
Symmetric array destructuring
Symmetric array destructuring within foreach
$data = [ [1, 'Tom'], [2, 'Fred'], ]; // list() style foreach ($data as list($id, $name)) { // logic here with $id and $name var_dump($id,$name); } // [] style foreach ($data as [$id, $name]) { // logic here with $id and $name var_dump($id,$name); }With named keys
$user = ['id' => 1, 'name' => 'Tom']; ['id' => $user_id, 'name' => $name] = $user; var_dump($user_id,$name); // with foreach $users = [ ['id' => 1, 'name' => 'Tom'], ['id' => 2, 'name' => 'Joe'] ]; foreach ($users as ['id' => $user_id, 'name' => $name]) { var_dump($user_id,$name); }