If you don’t know what destructuring is yet, it’s easier to start with an example:
$coords = [-48.876667, -123.393333];
list($latitude, $longitude) = $coords;
echo $latitude, ', ', $longitude;
// Output:
// -48.876667, -123.393333
Impressive? Then let’s move on!
Based on the official PHP documentation, destructuring is a language construct used to assign values to a list of variables in a single operation.
By the way, starting from PHP version 7.1, you can use [] instead of list. Therefore, the example above will change as follows:
$coords = [-48.876667, -123.393333];
[$latitude, $longitude] = $coords;
Even more beautiful!
For example, if the array contains more values than you need, you can simply skip it:
$point = [3, 14, 15];
[$x,, $z] = $point;
echo $x, ', ', $z;
// Output:
// 3, 15
You can also “unpack” an associative array, but in this case, you need to specify its keys:
$user = [
'first_name' => 'John',
'last_name' => 'Doe',
'age' => 71,
'job' => 'HR',
];
['first_name' => $firstName, 'last_name' => $lastName, 'job' => $job] = $user;
echo $firstName, ' ', $lastName, ' - ', $job;
// Output:
// John Doe - HR
When destructuring associative arrays, the order can be disregarded and elements can be skipped.
Sometimes in programming, there are moments when it is necessary to use the variable $tmp
, some of these cases can be solved using destructuring:
$a = 1;
$b = 2;
[$b, $a] = [$a, $b];
echo $a, ' ', $b;
// Output:
// 2 1
It’s very convenient to unpack an array in a foreach loop, as the inner part of the loop can look cleaner and simpler.
$users = [
[
'first_name' => 'John',
'last_name' => 'Doe',
],
[
'first_name' => 'Jane',
'last_name' => 'Doe',
],
];
foreach ($users as ['first_name' => $firstName, 'last_name' => $lastName]) {
echo $firstName, ' ', $lastName . "\n";
}
// Output:
// John Doe
// Jane Doe
The ideal candidates are parse_url
, pathinfo
, and other less popular functions.
['host' => $host] = parse_url("https://haprycon.dev/destructuring-in-php/");
echo $host;
// Output
// haprycon.dev
['extension' => $extension] = pathinfo('/var/www/html/images/picture.png');
echo $extension;
// Output:
// png
['month' => $month] = getdate();
echo $month;
// Output:
// November
$email = "contact@haprycon.dev";
[$username, $domain] = explode('@', $email);
echo $username, ' ', $domain;
For example, in the popular Bubble Sort algorithm, you can get rid of the variable $tmp:
$a = [2, 5, 12, 6, 2, 5, 7, 2, 4, 8];
for ($i = count($a) - 1; $i > 0; $i--) {
$swap = false;
for ($j = 0; $j < $i; $j++) {
if ($a[$j] > $a[$j + 1]) {
// With $tmp varialbe
// $tmp = $a[$j];
// $a[$j] = $a[$j+1];
// $a[$j+1] = $tmp;
// With destructuring and without $tmp variable
[$a[$j], $a[$j + 1]] = [$a[$j + 1], $a[$j]];
$swap = true;
}
}
if (!$swap) {
break;
}
}
function getResponse(): array
{
return ['error', 'Error message'];
}
[$status, $message] = getResponse();
echo 'Status: ', $status, ', Message: ', $message;
// Output
// Status: error, Message: Error message
Everything would be fine if it weren’t for the problems. For example, when destructuring an associative array without specifying keys, you will receive E_NOTICE or E_WARNING starting from PHP 8.
$user = ['first_name' => 'John', 'last_name' => 'Doe'];
[$firstName, $lastName] = $user;
// PHP < 8
// Notice: Undefined offset: 0
// Notice: Undefined offset: 1
// PHP >= 8
// Warning: Undefined array key 0
// Warning: Undefined array key 1
You will face the same issue if the index does not exist in the array.
$user = ['first_name' => 'John', 'last_name' => 'Doe'];
['age' => $age] = $user;
// PHP < 8
// Notice: Undefined index: age
// PHP >= 8
// Warning: Undefined array key "age"
$user = ['John', 'Doe'];
[$firstName, $lastName, $age] = $user;
// PHP < 8
// Notice: Undefined offset: 2
// PHP >= 8
// Warning: Undefined array key 2
We hope this article was helpful to you. Make your code better with destructuring. Good luck!