PHP foreach循环
foreach循环用于遍历数组元素。它只适用于数组和对象。如果尝试将其用于不同数据类型的变量,将会出现错误。
foreach循环根据元素而不是索引进行工作。它提供了一种最简单的方法来迭代数组的元素。
在foreach循环中,我们不需要递增值。
语法
foreach (array asvalue) {
//code to be executed
}
还有一种foreach循环的语法。
语法
foreach (array askey => $element) {
//code to be executed
}
流程图
示例1
使用foreach循环打印数组元素的PHP程序。
<?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
使用foreach循环打印关联数组元素的PHP程序。
<?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 : stash
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