PHP foreach语法
foreach语法结构提供了遍历数组的简单方式。foreach 仅能够应用于数组和对象,如果尝试应用于其他数据类型的变量,或者未初始化的变量将发出错误信息
每进行一次循环迭代,当前数组元素的值就会被赋值给$value变量,并且数组指针会逐一移动,直到到达最后一个数组元素。一般有两种方式:不取下标、取下标
【1】只取值,不取下标
foreach ($array as $value) {
code to be executed;
}
<?php
$colors = array("red","green","blue","yellow");
foreach ($colors as $value) {
echo "$value <br>";
}
?>
【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."<br>"; } ?>
本站声明:网站内容来源于网络,如有侵权,请联系我们https://www.qiquanji.com,我们将及时处理。
微信扫码关注
更新实时通知