使用 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
。