PHP list() assigns the values in the array to some variables in one step. Like array(), list() is not a true function, but a language construct.
Syntax:
void list( mixed var, mixed ... )
Note: list() can only be used on numerically indexed arrays and assumes that numerical indexing starts at 0.
The list() function in PHP is used to assign values to a set of variables in one operation.
Like array(), this is not really a function, but a language construct. List() is used to specify one of the variables in the list Job.
Example:
<?php $info = array('coffee', 'brown', 'caffeine'); // Listing all the variables list($drink, $color, $power) = $info; echo "$drink is $color and $power makes it special.n"; // Listing some of them list($drink, , $power) = $info; echo "$drink has $power.n"; // Or let's skip to only the third one list( , , $power) = $info; echo "I need $power!n"; // list() doesn't work with strings list($bar) = "abcde"; var_dump($bar); // NULL ?>
Example 1:
<?php $arr_age = array(18, 20, 25); list($wang, $li, $zhang) = $arr_age; echo $wang; //输出:18 echo $zhang; //输出:25 ?>
Example 2, data table query:
$result = mysql_query("SELECT id, username, email FROM user",$conn); while(list($id, $username, $email) = mysql_fetch_row($result)) { echo "用户名:$username<br />"; echo "电子邮箱:$email"; }
list() using array index
list() allows the use of another array to receive the values assigned by the array, but when using an index array, the order of assignment is opposite to the order listed in list():
$arr_age = array(18, 20, 25); list($a[0], $a[1], $a[2]) = $arr_age;
print_r($a);The output $a array structure is as follows:
Array ( [2] => 25 [1] => 20 [0] => 18 )
The above is the detailed content of Example usage of list() function in php and how to assign values in array to variables. For more information, please follow other related articles on the PHP Chinese website!