foreach语法结构提供了遍历数组的简单方式。foreach 仅能够应用于数组和对象,如果尝试应用于其他数据类型的变量,或者未初始化的变量将发出错误信息
每进行一次循环迭代,当前数组元素的值就会被赋值给$value变量,并且数组指针会逐一移动,直到到达最后一个数组元素。一般有两种方式:不取下标、取下标
【1】只取值,不取下标foreach ($array as $value) {
code to be executed;
}
$colors = array("red","green","blue","yellow");
foreach ($colors as $value) {
echo "$value
";
}
?>
【2】同时取下标和值foreach ($array as $index => $value) {
code to be executed;
}<?php
$colors = array(
"r"=>"red",
"g"=>"green",
"b"=>"blue",
"y"=>"yellow");
/*
r:red
g:green
b:blue
y:yellow
*/
foreach ($colors as $key => $value) {
echo $key.":".$value."
";
}
?>