PHP foreach遍历全指南
基本语法foreach用于遍历数组或可迭代对象语法如下foreach ($array as $value) { // 处理 $value }或同时获取键名和键值foreach ($array as $key $value) { // 处理 $key 和 $value }遍历索引数组遍历数字索引数组时默认仅获取元素值$colors [red, green, blue]; foreach ($colors as $color) { echo $color . \n; // 输出: red, green, blue }遍历关联数组需同时获取键名和键值时使用$key $value$user [name Alice, age 25]; foreach ($user as $key $value) { echo $key: $value\n; // 输出: name: Alice, age: 25 }引用修改原数组在$value前加可通过引用修改原数组元素$numbers [1, 2, 3]; foreach ($numbers as $num) { $num * 2; // 修改原数组 } print_r($numbers); // 输出: [2, 4, 6]注意遍历后需unset($num)避免后续操作误修改。遍历多维数组嵌套foreach可处理多维数组$matrix [[1, 2], [3, 4]]; foreach ($matrix as $row) { foreach ($row as $cell) { echo $cell . ; } echo \n; } // 输出: // 1 2 // 3 4遍历对象foreach支持实现Iterator接口的对象class MyIterator implements Iterator { private $items [a, b, c]; public function current() { return current($this-items); } public function key() { return key($this-items); } public function next() { next($this-items); } public function rewind() { reset($this-items); } public function valid() { return key($this-items) ! null; } } $iterator new MyIterator(); foreach ($iterator as $item) { echo $item . \n; // 输出: a, b, c }常见问题性能foreach比for更高效尤其处理关联数组。修改数组直接修改数组可能导致未定义行为建议使用引用或重新赋值。空数组若数组为空foreach会静默跳过不会报错。