foreach循环用于遍历数组元素。它仅适用于数组和对象。如果你尝试将其与其他数据类型的变量一起使用, 则会发出错误消息。
foreach循环基于元素而不是索引工作。它提供了一种最简单的方法来迭代数组的元素。
在foreach循环中, 我们不需要增加该值。
句法
foreach ($array as $value) {
//code to be executed
}
foreach循环还有另一种语法。
句法
foreach ($array as $key => $element) {
//code to be executed
}
流程图
范例1:
PHP程序使用foreach循环打印数组元素。
<?php
//declare array
$season = array ("Summer", "Winter", "Autumn", "Rainy");
//access array elements using foreach loop
foreach ($season as $element) {
echo "$element";
echo "</br>";
}
?>
输出
Summer
Winter
Autumn
Rainy
范例2:
PHP程序使用foreach循环打印关联数组元素。
<?php
//declare array
$employee = array (
"Name" => "Alex", "Email" => "alex_jtp@gmail.com", "Age" => 21, "Gender" => "Male"
);
//display associative array element through foreach loop
foreach ($employee as $key => $element) {
echo $key . " : " . $element;
echo "</br>";
}
?>
输出
Name : Alex
Email : alex_jtp@gmail.com
Age : 21
Gender : Male
范例3:
多维数组
<?php
//declare multi-dimensional array
$a = array();
$a[0][0] = "Alex";
$a[0][1] = "Bob";
$a[1][0] = "Camila";
$a[1][1] = "Denial";
//display multi-dimensional array elements through foreach loop
foreach ($a as $e1) {
foreach ($e1 as $e2) {
echo "$e2\n";
}
}
?>
输出
Alex Bob Camila Denial
范例4:
动态数组
<?php
//dynamic array
foreach (array ('j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't') as $elements) {
echo "$elements\n";
}
?>
输出
j a v a t p o i n t
评论前必须登录!
注册