Prerequisite
To fully understand this article, you should have a basic understanding of what arrays are and how they work in PHP. If you're new to arrays, watching the video below might help you grasp the concept more effectively:
What Is Array Destructuring?
Array destructuring is a way to extract elements from an array into separate variables easily. While it has been around in PHP for a while, it’s not commonly used. Let’s break it down with examples.
Destructuring Indexed/Numerical Arrays
Using the list() Construct
Consider the following array:
$brands = ['Apple', 'Dell', 'Lenovo'];
Without destructuring, you might write:
$apple = $brands[0];
$dell = $brands[1];
$lenovo = $brands[2];
With the list() construct, you can simplify this:
list($apple, $dell, $lenovo) = $brands;
// Alternatively, all on one line:
$brands = list($apple, $dell, $lenovo) = ['Apple', 'Dell', 'Lenovo'];
Skipping Elements
You can skip elements when destructuring:
// Extract only the last element
list(, , $lenovo) = ['Apple', 'Dell', 'Lenovo'];
While this works, it’s more practical to use loops for large arrays with many elements.
Using the Shorthand Syntax (Square Brackets)
Instead of list(), you can use square brackets for destructuring:
$brands = [$apple, $dell, $lenovo] = ['Apple', 'Dell', 'Lenovo'];
// Skipping an element
$brands = [$apple, , $lenovo] = ['Apple', 'Dell', 'Lenovo'];
Destructuring Associative Arrays
Given an associative array:
$person = ['name' => 'Jane Doe', 'age' => 24];
Using the list() Construct
Prior to PHP 7.1.0, list() worked only with indexed arrays. To check your PHP version, use:
echo PHP_VERSION . PHP_EOL;
For associative arrays:
list('name' => $name) = $person;
You can also extract specific keys without considering their order:
list('age' => $age) = $person;
Using the Shorthand Syntax
Here’s how to use square brackets for associative arrays:
['age' => $age] = $person;
Destructuring Nested Arrays
For nested arrays:
$person = [
'name' => 'Jane Doe',
'contacts' => [
'email' => 'jane@web.com',
'phone' => '234355663663'
]
];
[
'contacts' => [
'email' => $email
]
] = $person;
// echo $email;
Destructuring in Loops
You can destructure arrays directly within loops:
$people = [
['id' => '22222', 'name' => 'Jane Doe'],
['id' => '33333', 'name' => 'John Doe']
];
foreach ($people as ['id' => $id, 'name' => $name]) {
// echo $id . '<br />' . $name . '<br /><br />';
}
Destructuring in Practice
Consider a practical example with file uploads:
['name' => $n, 'type' => $t, 'size' => $s] = $_FILES['name_attr_val'];
Array destructuring simplifies code, making it more concise and readable. Whether working with indexed or associative arrays, it’s a valuable tool to include in your PHP toolbox.
Follow Me for More!
Stay connected for more tips, tutorials, and resources:
Happy coding!✌️❤️
Top comments (0)