使用 foreach
直接迴圈
foreach ($colors as $color) {
echo "I am the color $color<br>";
}
迴圈與鍵
$foods = ['healthy' => 'Apples', 'bad' => 'Ice Cream'];
foreach ($foods as $key => $food) {
echo "Eating $food is $key";
}
迴圈參考
在上面示例中的 foreach
迴圈中,直接修改值($color
或 $food
)不會更改其在陣列中的值。&
運算子是必需的,因此該值是指向陣列中元素的引用指標。
$years = [2001, 2002, 3, 4];
foreach ($years as &$year) {
if ($year < 2000) $year += 2000;
}
這類似於:
$years = [2001, 2002, 3, 4];
for($i = 0; $i < count($years); $i++) { // these two lines
$year = &$years[$i]; // are changed to foreach by reference
if($year < 2000) $year += 2000;
}
併發
可以在迭代期間以任何方式修改 PHP 陣列,而不會出現併發問題(與 Java List
s 不同)。如果通過引用迭代陣列,則稍後的迭代將受到對陣列的更改的影響。否則,對陣列的更改不會影響以後的迭代(就像你正在迭代陣列的副本一樣)。比較迴圈值:
$array = [0 => 1, 2 => 3, 4 => 5, 6 => 7];
foreach ($array as $key => $value) {
if ($key === 0) {
$array[6] = 17;
unset($array[4]);
}
echo "$key => $value\n";
}
輸出:
0 => 1
2 => 3
4 => 5
6 => 7
但如果陣列是參考迭代的,
$array = [0 => 1, 2 => 3, 4 => 5, 6 => 7];
foreach ($array as $key => &$value) {
if ($key === 0) {
$array[6] = 17;
unset($array[4]);
}
echo "$key => $value\n";
}
輸出:
0 => 1
2 => 3
6 => 17
4 => 5
的鍵值集不再迭代,6 => 7
變為 6 => 17
。