|
list (PHP 3, PHP 4, PHP 5) list --
把陣列中的值賦給一些變量
說明void list ( mixed varname, mixed ... )
像 array() 一樣,這不是真正的函數,而是語系結構。list()
用一步動作給一組變量進行賦值。
注:
list() 僅能用於數字索引的陣列並假定數字索引從 0 開始。
例子 1. list() 例子
<?php
$info = array('coffee', 'brown', 'caffeine');
// 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's skip to only the third one list( , , $power) = $info; echo "I need $power!\n";
?>
|
|
例子 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>
|
|
警示 |
list() 從最右邊一個參數開始賦值。若果你用單純的變量,不用擔心這一點。但是若果你用了具有索引的陣列,通常你期望得到的結果和在
list() 中寫的一樣是從左到右的,但實際上不是。是以相反順序賦值的。
|
例子 3. 在 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"
} |
|
參見 each(),array()
和 extract()。
| |