PHP foreach 关键词

定义和用法

foreach 关键字用于创建 foreach 循环,该循环会遍历数组中的每个元素,并对每个元素执行一段代码块。

相关页面

教程:PHP foreach 循环

实例

例子 1

打印数组中的所有值:

<?php
$cars = ["Ford", "Volvo", "BMW"];
foreach($cars as $car) {
  echo "$car <br>";
}
?>

亲自试一试

例子 2

打印关联数组中的键和值:

<?php
$people = [
  "Peter" => "35",
  "Ben" => "37",
  "Joe" => "43"
];

foreach($people as $person => $age) {
  echo "$person is $age years old";
  echo "<br>";
}
?>

亲自试一试