list() 用于在一次操作中给一组变量赋值。
注释:list()只用于数字索引的数组,且假定数字索引从 0 开始。
说明
list() 用数组中的元素为一组变量赋值。
注意,与 array() 类似,list() 实际上是一种语言结构,不是函数。
1.当数组是索引数组时
<?php
$my_array = array('Dog','Cat','Horse'); list($a, $b, $c) = $my_array; echo 'I have several animals, a '.$a.', a '.$b.' and a '.$c; ?>
正常输出结果:I have several animals, a Dog, a Cat and a Horse
2.当数组时关联数组时
$my_array = array('a'=>'Dog','b'=>'Cat','c'=>'Horse');
list($a, $b, $c) = $my_array; echo 'I have several animals, a '.$a.', a '.$b.' and a '.$c;
结果报错:
Notice: Undefined offset: 2 in D:\sfc\ceshi\6.php on line 3
Notice: Undefined offset: 1 in D:\sfc\ceshi\6.php on line 3
Notice: Undefined offset: 0 in D:\sfc\ceshi\6.php on line 3
I have several animals, a , a and a
3.当数组不是已0下标开始的数组时
<?php $my_array = array('1'=>'Dog','2'=>'Cat','3'=>'Horse'); list($a, $b, $c) = $my_array; echo 'I have several animals, a '.$a.',b '.$b.' and c '.$c;
结果如下:
Notice: Undefined offset: 0 in D:\sfc\ceshi\6.php on line 3
I have several animals, a ,b Dog and c Cat
分析:下标是1的元素的值赋给了$b变量,下标是2的元素的值赋给了$c变量,缺少下标是0的元素。