CleverCode found a method that returns multiple values by receiving a php function . It was often used in python before, and this method is also available in PHP.
<?php function retInfo() { $name = '张三'; $age = 18; $sex = 1; return array($name,$age,$sex); } list($name1,$age1,$sex1) = retInfo(); echo "name:${name1},age:${age1},sex:${sex1}\r\n"; list($name2,$age2,$sex2) = array('李四',19,2); echo "name:${name2},age:${age2},sex:${sex2}\r\n"; ?>
list()
PHP list() Use one step to assign the values in the array to somevariable. 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 from 0.
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 reversed from the order listed in list():
$arr_age = array(18, 20, 25); list($a[0], $a[1], $a[2]) = $arr_age; print_r($a);
Output The $a array structure is as follows:
Array ( [2] => 25 [1] => 20 [0] => 18 )
The above is the detailed content of How to use list() function in php to assign values in array to variables. For more information, please follow other related articles on the PHP Chinese website!