PHP list() Function
The PHP list() is not really a function, but a language construct and used to assign values to a list of variables in one operation.
Note: Before PHP 7.1.0, list() only worked on numerical arrays and assumes the numerical indices start at 0.
Syntax
list(var, vars)
Parameters
var |
Required. Specify a variable to assign a value to. |
vars |
Optional. Specify a variable to assign a value to. Multiple parameters are allowed. |
Return Value
Returns the assigned array.
Example: list() example
The example below shows the usage of list() function.
<?php $info = array("John", 25, "London"); //listing all the variables list($name, $age, $city) = $info; echo "$name is $age years old. He lives in $city.\n"; //listing some of them list($name, , $city) = $info; echo "$name lives in $city.\n"; //skip to the third one list( , , $city) = $info; echo "I love $city!\n"; //list() doesn't work with strings list($city) = "London"; var_dump($city); ?>
The output of the above code will be:
John is 25 years old. He lives in London. John lives in London. I love London! NULL
Example: using nested list()
The example below shows how to use nested list.
<?php $info = array("John", array(25, "London")); //listing all the variables list($name, list($age, $city)) = $info; echo "$name is $age years old. He lives in $city."; ?>
The output of the above code will be:
John is 25 years old. He lives in London.
Example: list() with keys
A list with keys can also be used where mixing of integer and string keys are allowed. However, elements with and without keys cannot be mixed. Consider the example below:
<?php $info1 = array('name'=>'John', 'age'=>25, 'city'=>'London'); //listing variables (with string keys) list('name'=>$x, 'age'=>$y, 'city'=>$z) = $info1; echo "$x is $y years old. He lives in $z.\n"; $info2 = array('name'=>'Marry', 'London', 'Paris'); //listing variables (with mixed keys) list('name'=>$a, 0=>$c, 1=>$d) = $info2; echo "$a moved from $c to $d recently."; ?>
The output of the above code will be:
John is 25 years old. He lives in London. Marry moved from London to Paris recently.
❮ PHP Array Reference