PHP7.1 square brackets array symbol multi-value replication and Usage Analysis of specified key value assignment, php7.1 square brackets
This example describes how to copy multiple values of the array symbol in square brackets (PHP7.1) and assign values to the specified key values. We will share this with you for your reference. The details are as follows:
PHPer may all know the usage of list. Simply put, you can assign values to multiple variables through arrays in an expression test:
$values = array('value1', 'value2');$list($v1, $v2) = $values;
Is it convenient? In PHP 7.1, it can also save some trouble:
[$v1, $v2] = ['foo', 'bar'];
This is not the most powerful. in PHP 7.1, we can also specify key values to assign values, so that we do not need to care about the order of array elements:
list('v1' => $value1, 'v2' => $value2) = array('v1' => 'foo', 'v2' => 'bar', ...);// or['v1' => $value1, 'v2' => $value2] = ['v1' => 'foo', 'v2' => 'bar', ...];
In fact, in the age of PHP 5, list has a very good usage which may be unfamiliar to everyone:
$arr = [ ['x', 'y'], ['x1', 'y2'],];foreach ($arr as list($x, $y)) { echo $x, ' ', $y, PHP_EOL;}
In PHP 7.1, the key value assignment can be specified, which is more flexible and more common:
$arr = [ ['x' => 1, 'y' => '2'], ['x' => 2, 'y' => '4'],];foreach ($arr as ['x' => $x, 'y' => $y)) { echo $x, ' ', $y, PHP_EOL;}
Let's take a look at the example on the official website. Does it feel as fresh as the spring breeze:
Class ElePHPant {private $ name, $ color, $ age, $ cuteness; public function _ construct (array $ attributes) {// $ this-> name = $ attributes ['name']; // before // now ["name" => $ this-> name, "color" => $ this-> color, "age" => $ this-> age, "cuteness" => $ this-> cuteness] = $ attributes ;} //...}
It is worth mentioning that the value assignment method can be nested!
[[$a, $b], [$c, $d]] = [[1, 2], [3, 4]];
Finally, there is an outlook in the proposal of PHP 7.1, which is also worth looking forward:
class ElePHPant{ private $name, $colour, $age, $cuteness; public function __construct(["name" => string $name, "colour" => \Colour $colour, "age" => int $age, "cuteness" => float $cuteness]) { $this->name = $name; $this->colour = $colour; $this->age = $age; $this->cuteness = $cuteness; } // ...}
If PHP introduces this syntax, the parameter list will no longer care about the Parameter order, and PHP's friends will no longer envy Ruby's friends!