Please wait

Destructuring Arrays

In PHP, array destructuring, also known as array unpacking, is a feature that allows you to assign elements of an array or properties of an object to separate variables in a single statement. It's a handy way to extract multiple values from an array or object at once.

The problem

Consider the following array:

$data = ['Alice', 30, 'Engineer'];

Traditionally, if you wanted to assign each of these values to a separate variable, you would have to do it individually like this:

$name = $data[0];
$age = $data[1];
$profession = $data[2];

Destructuring the array

But with array destructuring, you can do this in one line:

list($name, $age, $profession) = $data;

After this line, $name would contain 'Alice', $age would contain 30, and $profession would contain 'Engineer'. You can then use these variables in your code as you see fit.

We can use the list keyword to instruct PHP to extract the values from the $data variable.

The variables on the left-hand side of the assignment must match the number of elements in the array. If there are fewer variables than array elements, the remaining elements will not be assigned.

An alternative syntax to the list keyword is to wrap the variables with the [] characters. It's shorter than using list.

[$name, $age, $profession] = $data;

However, list() is less flexible because it only works with numerically indexed arrays and doesn't support skipping values or nested destructuring.

Associative arrays

Array destructuring works with associative arrays, too. The keys in the array do not need to be in order.

$data = [ 'name' => 'Alice', 'age' => 30, 'profession' => 'Engineer'];
 
['name' => $name, 'age' => $age, 'profession' => $profession] = $data;

Skipping values

You can also skip values in the array that you're not interested in by leaving empty spaces.

$data = ['Alice', 30, 'Engineer'];
[$name, , $profession] = $data;
// $name will be 'Alice', $profession will be 'Engineer', 30 is ignored

Key takeaways

  • Array destructuring in PHP is a way to assign values from an array to variables in a single statement.
  • The number of variables and array elements should match. If not, the remaining array elements are ignored, or extra variables get a NULL value.
  • By leaving empty spaces, you can skip over values in the array you're not interested in.
  • list was used for a similar purpose prior to PHP 7.1, but it has limitations compared to modern array destructuring.
  • Despite making the code more concise, improper use of array destructuring can lead to code that is harder to read and understand. Balance is key.

Comments

Please read this before commenting