How to use list() function in php to assign values ​​in array to variables

黄舟
Release: 2023-03-14 09:52:01
Original
1851 people have browsed it

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 = &#39;张三&#39;;
    $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(&#39;李四&#39;,19,2);

echo "name:${name2},age:${age2},sex:${sex2}\r\n";


?>
Copy after login


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
?>
Copy after login

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";
}
Copy after login

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);
Copy after login

Output The $a array structure is as follows:

Array ( [2] => 25 [1] => 20 [0] => 18 )
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template