TIL: Destructure arrays at the righthand part of a foreach loop

In PHP arrays can be destructured using the [] (as of PHP 7.1) or the list() language constructs.

However, today I learned that you can use array destructuring as the righthand part of a foreach loop.

Here's an example:

$users = [
  ['name' => 'Taylor', 'surname' => 'Otwell', 'email' => 'taylor@example.com'],
	['name' => 'Jess', 'surname' => 'Archer', 'email' => 'jess@example.com'],
];

foreach($users as ['name' => $name, 'surname' => $surname, 'email' => $email]) {
  dump("User {$name} with Email {$email}");
}

// "User Taylor with Email taylor@example.com"
// "User Jess with Email jess@example.com"

If the array has multiple keys ans you are only interested in one, you can do that too:

$users = [
  ['name' => 'Taylor', 'surname' => 'Otwell', 'email' => 'taylor@example.com'],
	['name' => 'Jess', 'surname' => 'Archer', 'email' => 'jess@example.com'],
];

foreach($users as ['email' => $email]) {
  dump($email);
}

// "taylor@example.com"
// "jess@example.com

Pretty interesting 🙂