函式名稱: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() 函式只能用於索引陣列或者關聯陣列,不能用於物件。