Destructuring Assignment in PHP 7.1

Destructuring assignment is a syntax used to unpack values from array or object into different variables. This is used to ease our job as a programmer. This means we can make an associative array keys into different variables. Instead of running several assignment operations, we can just use one destructuring assignment.

There are 2 ways in PHP to destructure an array. Destructuring assignment is similar to an ordinary assigment. We’ll be putting the array to be destructured on the right side of the equal (‘=’) sign. The first syntax would be using list():

$arr = ['a', 'b', 'c'];
list($a, $b, $c) = $arr;

Similarly, the second syntax would be using [].

$arr = ['a', 'b', 'c'];
[$a, $b, $c] = $arr;

If we run the 2 syntax above, we will get the same result. The result assigning first element of the array into $a, second element into $b, and third element into $c. When we run the code, we can see that $a contains ‘a’, $b contains ‘b’, and $c contains ‘c’.

Now, what if we want to destructure an associative array? We can still use the same syntax, but we’ll be adding the ‘=>’ operator to determine what value goes to what variable. This is similar with creating an associative array. Here’s the syntax to do it:

$arr = ['first_name' => 'John', 'last_name' => 'Doe'];
['first_name' => $first_name, 'last_name' => $last_name] = $arr; //We can use this
list('first_name' => $first_name, 'last_name' => $last_name) = $arr; //Or we can use this

After we run the code, we’ll have $first_name filled with ‘John’ and $last_name variable filled with ‘Doe’. We can also use this syntax with object, with a modification of course. To destructure an object, we’ll need to convert the object into an associative array. After that, we’ll use the same syntax as above to destructure our object. We can use a function called get_object_vars() to convert our object into an associative array.

class User {
  public $name;
  public $address;
}
$user = new User();
$user->name = "John";
$user->address = "Address";

$arr = get_object_vars($user); //Convert into associative array, then run the destructuring assignment
['name' => $name, 'address' => $address] = $arr;

In short, we can use both list() and [] to destructure an associative array. If we want to destructure an object, we can convert it into an associative array with get_object_vars() first.