Home > Backend Development > PHP Tutorial > Example usage of list() function in php and how to assign values ​​in array to variables

Example usage of list() function in php and how to assign values ​​in array to variables

伊谢尔伦
Release: 2023-03-11 08:14:02
Original
1693 people have browsed it

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

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(&#39;coffee&#39;, &#39;brown&#39;, &#39;caffeine&#39;);
// 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&#39;s skip to only the third one
list( , , $power) = $info;
echo "I need $power!n";
// list() doesn&#39;t work with strings
list($bar) = "abcde";
var_dump($bar); // NULL
?>
Copy after login

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 opposite to the order listed in list():

$arr_age = array(18, 20, 25);
list($a[0], $a[1], $a[2]) = $arr_age;
Copy after login

print_r($a);The output $a array structure is as follows:

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

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!

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