Home >Backend Development >PHP Tutorial >深入解析php中的foreach函数_PHP

深入解析php中的foreach函数_PHP

WBOY
WBOYOriginal
2016-06-01 12:03:44860browse

Foreach 函数(PHP4/PHP5)
foreach 语法结构提供了遍历数组的简单方式。
foreach 仅能够应用于数组和对象,如果尝试应用于其他数据类型的变量,或者未初始化的变量将发出错误信息。

有两种语法:
复制代码 代码如下:
foreach (array_expression as $value)
    statement
foreach (array_expression as $key => $value)
    statement

例子1:
复制代码 代码如下:
$arr=array(1,2,3,4);
foreach($arr as $value){
  echo $value."
";
}
?>

例子2:
复制代码 代码如下:
$arr=array(1,2,3,4);
foreach($arr as $key=>$value){
  echo $key."=====>".$value."
";
}
?>

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn