函数名称:list()
适用版本:所有版本
函数描述: list() 函数用于将数组中的值赋给一组变量。
语法: list(variable1, variable2, ...)
参数说明:
- variable1, variable2, ...:要赋值的变量。
返回值: 该函数没有返回值。
示例:
- 基本用法
$array = array('apple', 'banana', 'orange');
list($fruit1, $fruit2, $fruit3) = $array;
echo $fruit1; // 输出:apple
echo $fruit2; // 输出:banana
echo $fruit3; // 输出:orange
- 忽略某些值
$array = array('apple', 'banana', 'orange');
list($fruit1, , $fruit3) = $array;
echo $fruit1; // 输出:apple
echo $fruit3; // 输出:orange
- 与函数返回值结合使用
function getFruits() {
return array('apple', 'banana', 'orange');
}
list($fruit1, $fruit2, $fruit3) = getFruits();
echo $fruit1; // 输出:apple
echo $fruit2; // 输出:banana
echo $fruit3; // 输出:orange
- 结合索引数组和关联数组
$array = array('apple', 'banana', 'color' => 'orange');
list($fruit1, $fruit2, $color) = $array;
echo $fruit1; // 输出:apple
echo $fruit2; // 输出:banana
echo $color; // 输出:orange
注意事项:
- 数组的键名和变量的顺序要一一对应,如果键名不存在,则对应的变量将被赋值为 NULL。
- 如果数组中的元素数量小于变量的数量,多余的变量将被忽略。
- list() 函数只能用于索引数组或者关联数组,不能用于对象。