# 对称阵列解构

**官方解释：**&#x77ED;数组语法（*\[]*）现在可以用于将数组的值赋给一些变量（包括在*foreach*中）。 这种方式使从数组中提取值变得更为容易。

以下是官方示例：**但是经过我测试（PHP Version 7.1.5），是一个错误的例子**

```php
<?php
$data = [
    ['id' => 1, 'name' => 'Tom'],
    ['id' => 2, 'name' => 'Fred'],
];

while (['id' => $id, 'name' => $name] = $data) {
    // logic here with $id and $name
}
```

我们知道在 PHP5.4 之前只能通过 `array()` 来定义数组，5.4之后添加了 `[]` 的简化写法（省略了5个字符还是很实在的）。

```php
<?php
// 5.4 之前
$array = array(1, 2, 3);
$array = array("a" => 1, "b" => 2, "c" => 3);

// 5.4 及之后
$array = [1, 2, 3];
$array = ["a" => 1, "b" => 2, "c" => 3];
```

引申到另外一个问题上，如果我们要把数组的值赋值给不同的变量，可以通过 `list` 来实现：

```php
<?php
list($a, $b, $c) = $array;

list($a,$b)=array(10,20);
echo $a,'~',$b,'<br />';
//返回10~20

list($a,$b,,$c)=array(2=>10,3=>20,4=>30,1=>40);
echo $a,'~',$b,'~',$c,'<br />';
//返回notice~40~20
//执行到$a的时候返回给我一个notice：说数组没有0键
```

为什么会返回这个notice\~40\~20呢？ [查看解释](http://www.cnblogs.com/ggbd-lie/p/3269192.html)

PHP7.1 实现了一下特性。但是要注意的是：出现在左值中的 `[]` 并不是数组的简写，是 `list()` 的简写。

但是并不仅仅如此，新的 `list()` 的实现并不仅仅可以出现在左值中，也能在 `foreach` 循环中使用：

```php
$data = [
    ['id' => 1, 'name' => 'Tom'],
    ['id' => 2, 'name' => 'Fred'],
];


foreach ($data as ['id' => $id, 'name' => $name]) {
    echo $id . PHP_EOL;
    echo $name. PHP_EOL;
}
```

结果：

```
id:1 name:Tom id:2 name:Fred
```

不过因为实现的问题，`list()`和`[]`不能相互嵌套使用：


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://php7.shujuwajue.com/php-71x-xin-te-xing/xin-te-xing/dui-cheng-zhen-lie-jie-gou.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
