Destructuring pulls values out of an array into separate variables in one step.
<?php
$point = [10, 20];
[$x, $y] = $point;
echo "x=$x, y=$y";
x=10, y=20
Without it, you would write $x = $point[0]; $y = $point[1];.
Skip items
Leave a gap with an empty slot.
<?php
[$first, , $third] = ["a", "b", "c"];
echo $first . $third;
ac
With keys
For an associative array, name the keys you want.
<?php
$user = ["name" => "Isha", "city" => "Kochi", "age" => 29];
["name" => $name, "city" => $city] = $user;
echo "$name from $city";
Isha from Kochi
Nested arrays
<?php
$data = ["Ravi", [28, "Pune"]];
[$name, [$age, $city]] = $data;
echo "$name, $age, $city";
Ravi, 28, Pune
In a foreach loop
This is where destructuring saves the most space.
<?php
$products = [
["Pen", 12],
["Book", 250],
];
foreach ($products as [$name, $price]) {
echo "$name costs $price\n";
}
Pen costs 12
Book costs 250
With keys:
<?php
$users = [
["id" => 1, "name" => "Ana"],
["id" => 2, "name" => "Ben"],
];
foreach ($users as ["id" => $id, "name" => $name]) {
echo "#$id $name\n";
}
#1 Ana
#2 Ben
Return several values from a function
<?php
function splitName(string $full): array
{
return explode(" ", $full, 2);
}
[$first, $last] = splitName("Ada Lovelace");
echo "$last, $first";
Lovelace, Ada
Swap two variables
<?php
$a = 1;
$b = 2;
[$a, $b] = [$b, $a];
echo "$a $b";
2 1
Missing items
If the array has fewer items than you ask for, PHP gives null plus a warning.
<?php
[$a, $b] = [1];
var_dump($b);
Warning: Undefined array key 1 in /path/to/index.php on line 2
NULL
list() is the older form
list($a, $b) = $array; does the same as [$a, $b] = $array;. You will meet it in old code. Use the square brackets in new code.
Name things as you unpack
[$lat, $lng] = $coordinates; documents the meaning of each position right where you use it.