The function, list() is used to assign a list of variables in one operation only as if they were an array.
![](http://findnerd.s3.amazonaws.com/imagedata/8253/8253.png)
In php7.1 list() function will not assign variables in reverse order.
The syntax of the list() function is:
list($array1, $array2, $array3) = array(value1,value2,value3);
Example:
list($array[],$array[],$array[]) = [1,2,3,];
var_dump($array);
// in php7.1 results in $array = [1,2,3] not in $array = [3,2,1].
prior, in php 5.4 a short array syntax was used which made array easier to use and now in php7.1 instead of using list() function syntax we can use square brackets "[]" to assign variables from array..
Means you can use any of the way, either list() or square brackets [].
let's see the simple example:
list($firstName, $lastName) = ["John", "Doe"];
/*
equivalent to :
$firstName = "John";
$lastName = "Doe";
*/
//or
[$firstName, $lastName] = ["John", "Doe"];
The list() function now have a great feature that is, It supports keys in list before that only numerical indexed arrays were used. Now list function also support associative arrays.
Example:
$user = [ "first_name" => "John", "last_name" => "Doe"];
["first_name" => $firstName, "last_name" => $lastName]= $user;
We can also define multidimensional arrays inside list function as:
Example:
$users = [
["name" => "John Doe", "age" => 29],
["name" => "Sam", "age" => 36]
];
[["name" => $name1, "age" => $age1],["name" => $name2, "age" => $age2]] = $users;
The list constructs now not allowed to be assigned as empty and unpacked.
Example:
list() = $a;
//empty array not allowed.
0 Comment(s)