©
本文档使用 PHP中文网手册 发布
(PHP 4, PHP 5, PHP 7)
list — 把数组中的值赋给一些变量
$varname
[, mixed $...
] )像 array() 一样,这不是真正的函数,而是语言结构。 list() 用一步操作给一组变量进行赋值。
varname
一个变量。
返回指定的数组。
Example #1 list() 例子
<?php
$info = array( 'coffee' , 'brown' , 'caffeine' );
// 列出所有变量
list( $drink , $color , $power ) = $info ;
echo " $drink is $color and $power makes it special.\n" ;
// 列出他们的其中一个
list( $drink , , $power ) = $info ;
echo " $drink has $power .\n" ;
// 或者让我们跳到仅第三个
list( , , $power ) = $info ;
echo "I need $power !\n" ;
// list() 不能对字符串起作用
list( $bar ) = "abcde" ;
var_dump ( $bar ); // NULL
?>
Example #2 list() 用法的一个例子
<table>
<tr>
<th>Employee name</th>
<th>Salary</th>
</tr>
<?php
$result = mysql_query ( "SELECT id, name, salary FROM employees" , $conn );
while (list( $id , $name , $salary ) = mysql_fetch_row ( $result )) {
echo " <tr>\n" .
" <td><a href=\"info.php?id= $id \"> $name </a></td>\n" .
" <td> $salary </td>\n" .
" </tr>\n" ;
}
?>
</table>
Example #3 使用嵌套的 list()
<?php
list( $a , list( $b , $c )) = array( 1 , array( 2 , 3 ));
var_dump ( $a , $b , $c );
?>
int(1) int(2) int(3)
Example #4 在 list() 中使用数组索引
<?php
$info = array( 'coffee' , 'brown' , 'caffeine' );
list( $a [ 0 ], $a [ 1 ], $a [ 2 ]) = $info ;
var_dump ( $a );
?>
产生如下输出(注意单元顺序和 list() 语法中所写的顺序的比较):
array(3) { [2]=> string(8) "caffeine" [1]=> string(5) "brown" [0]=> string(6) "coffee" }
list() 从最右边一个参数开始赋值。如果你用单纯的变量,不用担心这一点。 但是如果你用了具有索引的数组,通常你期望得到的结果和在 list() 中写的一样是从左到右的,但实际上不是。 它是以相反顺序赋值的。
在 list() 执行过程中修改数组(比如使用 list($a, $b) = $b)将会产生不可预知的结果。
Note:
list() 仅能用于数字索引的数组并假定数字索引从 0 开始。
[#1] Colin Guthrie [2015-07-20 13:41:53]
If you want use the undefined behaviour as you might expect it e.g. if you want:
$b = ['a','b']; list($a, $b) = $b;
to result in $a=='a' and $b=='b', then you can just cast $b to an array (even although it already is) to create a copy. e.g.
$b = ['a','b']; list($a, $b) = (array)$b;
and get the expected results.
[#2] mogwai512 [2015-06-21 05:54:55]
I see many people offer solutions about the flipped order of the list construct. All you have to do is this:
<?php
$info = array('coffee', 'brown', 'caffeine');
$a = list($a[0], $a[1], $a[2]) = $info;
var_dump($a);
?>
. . . and your info will be in the correct order. You can also just assign a new var to the list and it will still work:
<?php
$info = array('coffee', 'brown', 'caffeine');
$b = list($a[0], $a[1], $a[2]) = $info;
var_dump($b);
?>
[#3] mdessaintes at gmail dot com [2015-05-18 08:25:30]
Assignement is from right to left so this result in unexpected behavior:
<?php
$str = ['123456', 'abcdef'];
list($num, $str) = $str;
var_dump($num, $str);
?>
outputs :
string 'a' (length=1)
string 'abcdef' (length=6)
[#4] grzeniufication [2014-10-21 10:35:50]
The example showing that:
$info = array('kawa', 'br?zowa', 'kofeina');
list($a[0], $a[1], $a[2]) = $info;
var_dump($a);
outputs:
array(3) {
[2]=>
string(8) "kofeina"
[1]=>
string(5) "br?zowa"
[0]=>
string(6) "kawa"
}
One thing to note here is that if you define the array earlier, e.g.:
$a = [0, 0, 0];
the indexes will be kept in the correct order:
array(3) {
[0]=>
string(4) "kawa"
[1]=>
string(8) "br?zowa"
[2]=>
string(7) "kofeina"
}
Thought that it was worth mentioning.
[#5] vickyssj7 at gmail dot com [2014-09-01 17:21:35]
if we assign array's each value individual key('numeric only'), and use the array indices in list(),, then it output the reverse order of array keys--
BUT THE HIGHER KEY VALUE ("2" in this e.g below) WILL GET THE FIRST PLACE IN THE ARRAY IN RETURN, MEANS IT PUSHES THE VALUE WITH HIGHER KEY IN PLACE OF FIRST KEY VALUE, so it also gives higher key value the first priority while reversing the order of the keys and replacing the lower key value with the higher key value.
$value = array( 0 => 'low', 2 => 'medium', 1 => 'higher');
list($a[2], $a[1], $a[0]) = $value;
var_dump($a);
//Outputs:---
array(3) {
[0] => string(6) "medium"
[1] => string(6) "higher"
[2] => string(3) "low"
}
[#6] Thanos K. [2014-03-13 17:36:59]
Also it seems that it doesn't work as expected with arrays with non numeric keys:
list($k, $l, $m) = array('a' => 'val1', 'b' => 'val2', 'c' => 'val3');
Gives empty variables..
[#7] edam [2014-02-04 15:18:40]
This doesn't work on associative array. For example:
list( $a, $b, $c ) = array( 'a' => 'a', 'b' => 'b', 'c' => 'c' );
PHP Notice: Undefined offset: 2 in Command line code on line 1
PHP Notice: Undefined offset: 1 in Command line code on line 1
PHP Notice: Undefined offset: 0 in Command line code on line 1
[#8] john at jbwalker dot com [2013-12-08 00:31:09]
The list construct seems to look for a sequential list of indexes rather taking elements in sequence. What that obscure statement means is that if you unset an element, list will not simply jump to the next element and assign that to the variable but will treat the missing element as a null or empty variable:
$test = array("a","b","c","d");
unset($test[1]);
list($a,$b,$c)=$test;
print "\$a='$a' \$b='$b' \$c='$c'<BR>";
results in:
$a='a' $b='' $c='c'
not:
$a='a' $b='c' $c='d'
[#9] megan at voices dot com [2013-09-10 15:45:57]
As noted, list() will give an error if the input array is too short. This can be avoided by array_merge()'ing in some default values. For example:
<?php
$parameter = 'name';
list( $a, $b ) = array_merge( explode( '=', $parameter ), array( true ) );
?>
However, you will have to array_merge with an array long enough to ensure there are enough elements (if $parameter is empty, the code above would still error).
An alternate approach would be to use array_pad on the array to ensure its length (if all the defaults you need to add are the same).
<?php
$parameter = 'bob-12345';
list( $name, $id, $fav_color, $age ) = array_pad( explode( '-', $parameter ), 4, '' );
var_dump($name, $id, $fav_color, $age);
?>
[#10] Arne [2013-07-31 13:30:47]
list() will give an error if the input array is too short. This can be avoided by array_merge()'ing in some default values. For example:
<?php
$parameter = 'name';
list( $a, $b ) = array_merge( explode( '=', $parameter ), array( true ) );
?>
[#11] Achilles at thegreatwarrior dot com [2013-07-14 00:58:03]
Second, when you??re using the list() function, you must acknowledge each array element. You could not do this
list($weekday, $month) = $date;
But you can use empty values to ignore elements:
list ($weekday, , $month) = $date;
[#12] Matt [2013-05-25 16:40:38]
You can't type check within the list() parameters:
list ( array $var1, $var2 ) = array ( array('one','two'), 'three');
generates a parse error, unexpected 'array'.
[#13] srikanth at networthindia dot com [2013-02-09 12:34:48]
Note: list cannot assign array cast of object to variables straight away. first you need to convert the object to numeric indexed array.
ex:
list($a, $b, $d) = (array) $abc; // $abc is an object; this will not assign.
list($a, $b, $c) = array_values((array) $abc); // This will work.
[#14] svennd [2012-12-23 19:08:43]
The list() definition won't throw an error if your array is longer then defined list.
<?php
list($a, $b, $c) = array("a", "b", "c", "d");
var_dump($a); // a
var_dump($b); // b
var_dump($c); // c
?>
[#15] chris at chlab dot ch [2012-11-07 15:00:04]
The example states the following:
<?php
// list() doesn't work with strings
list($bar) = "abcde";
var_dump($bar);
// output: NULL
?>
If the string is in a variable however, it seems using list() will treat the string as an array:
<?php
$string = "abcde";
list($foo) = $string;
var_dump($foo);
// output: string(1) "a"
?>