PHP4 (PHP3 並沒有) 加入了 foreach 的功能。這功能在 PERL 和其他語言中都有。 用它可以很方便地存取陣列。 合法的句式有兩個: 第二個只是對第一個句法作了一點改動但很有用。如下:
第一個句式每次循環都會把陣列 array_expression 中的一個元素的值存到變數 $value 中直到陣列中所有的元素用完了。
第二個句式和第一個差不多, 分別在於除了 $value 會儲存了元素的值, $key 還會儲存了目前元素的索引號。
備注: 當 foreach 開始時內置的陣列指標會指向陣列的首個元素的位置。 這代表你不必在每次 foreach 前調用 reset() 函數。
備注: Also note that foreach operates on a copy of the specified array, not the array itself, therefore the array pointer is not modified like with the each construct.
在下面的範例, 你應可看出它們功能是一樣的:
reset ($arr); while (list(, $value) = each ($arr)) { echo "Value: $value<br>\n"; } foreach ($arr as $value) { echo "Value: $value<br>\n"; } |
reset ($arr); while (list($key, $value) = each ($arr)) { echo "Key: $key; Value: $value<br>\n"; } foreach ($arr as $key => $value) { echo "Key: $key; Value: $value<br>\n"; } |
更多的示範:
/* foreach example 1: value only */ $a = array (1, 2, 3, 17); foreach ($a as $v) { print "Current value of \$a: $v.\n"; } /* foreach example 2: value (with key printed for illustration) */ $a = array (1, 2, 3, 17); $i = 0; /* for illustrative purposes only */ foreach($a as $v) { print "\$a[$i] => $v.\n"; } /* foreach example 3: key and value */ $a = array ( "one" => 1, "two" => 2, "three" => 3, "seventeen" => 17 ); foreach($a as $k => $v) { print "\$a[$k] => $v.\n"; } |