foreach 语句用于循环遍历数组。每进行一次循环,当前数组元素的值就会被赋值给 value 变量(数组指针会逐一地移动) – 以此类推。
语法如下:
foreach (array as value) { code to be executed; }
Program List:循环输出数组的值
<?php $arr = array("one", "two", "three"); foreach ($arr as $value) { echo "Value: " . $value . "<br />"; } ?>
程序运行结果:
Value: one Value: two Value: three
Program List:循环输出数组的引用
从PHP 5开始,你可以通过在变量前面使用&操作符来修改数组的元素,这样的话分配的是引用,而不是值。
<?php $arr = array(1, 2, 3, 4); foreach ($arr as &$value) { $value = $value * 2; print $value.'<br />'; } // $arr is now array(2, 4, 6, 8) unset($value); // break the reference with the last element ?>
程序运行结果:
2 4 6 8
Program List:配合list()使用
<?php $arr = array("Apple", "Banana", "Orange"); reset($arr); while (list(, $value) = each($arr)) { echo "Fruit: $value<br />\n"; } foreach ($arr as $value) { echo "Fruit: $value<br />\n"; } ?>
程序运行结果:
Fruit: Apple Fruit: Banana Fruit: Orange Fruit: Apple Fruit: Banana Fruit: Orange
Program List:输出键与值
<?php $arr = array("Apple", "Banana", "Orange"); 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"; } ?>
程序运行结果:
Key: 0; Value: Apple Key: 1; Value: Banana Key: 2; Value: Orange Key: 0; Value: Apple Key: 1; Value: Banana Key: 2; Value: Orange
Program List:更多foreach的使用例子
<?php /* foreach example 1: value only */ $a = array(1, 2, 3, 17); foreach ($a as $v) { echo "Current value of \$a: $v.\n"; } /* foreach example 2: value (with its manual access notation printed for illustration) */ $a = array(1, 2, 3, 17); $i = 0; /* for illustrative purposes only */ foreach ($a as $v) { echo "\$a[$i] => $v.\n"; $i++; } /* foreach example 3: key and value */ $a = array( "one" => 1, "two" => 2, "three" => 3, "seventeen" => 17 ); foreach ($a as $k => $v) { echo "\$a[$k] => $v.\n"; } /* foreach example 4: multi-dimensional arrays */ $a = array(); $a[0][0] = "a"; $a[0][1] = "b"; $a[1][0] = "y"; $a[1][1] = "z"; foreach ($a as $v1) { foreach ($v1 as $v2) { echo "$v2\n"; } } /* foreach example 5: dynamic arrays */ foreach (array(1, 2, 3, 4, 5) as $v) { echo "$v\n"; } ?>
探讨PHP控制结构foreach的用法