Home > Backend Development > PHP Tutorial > foreach loop statement in PHP

foreach loop statement in PHP

巴扎黑
Release: 2023-03-04 12:10:01
Original
1564 people have browsed it

One syntax

foreach(array_expression as $value)

statement;

foreach(array_expression as $key=>$value)

statement;

The foreach statement will traverse the array array_expression. Each time it loops, the value in the current array is assigned to $value (or $key and $value). At the same time, the pointer of the array moves backward until After the traversal is completed, the array pointer will be automatically reset when using foreach, so there is no need to manually set the position of the pointer.

2 Example

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>应用foreach语句遍历数组</title>
</head>
<style type="text/css">
<!--
.STYLE1 {font-size: 13px;
       color: #FF0000;
font-weight: bold;
}
.STYLE2 {font-size: 13px;
      
}
-->
</style>
<body>
<?php
$name = array("1"=>"品牌笔记本电脑","2"=>"高档男士衬衫","3"=>"品牌3G手机","4"=>"高档女士挎包");
$price = array("1"=>"4998元","2"=>"588元","3"=>"4666元","4"=>"698元");
$counts = array("1"=>1,"2"=>1,"3"=>2,"4"=>1);
echo &#39;<table width="580" border="1" cellpadding="1" cellspacing="1" bordercolor="#FFFFFF" bgcolor="#FF0000">
          <tr>
            <td width="145" align="center" bgcolor="#FFFFFF"  class="STYLE1">商品名称</td>
            <td width="145" align="center" bgcolor="#FFFFFF"  class="STYLE1">价 格</td>
            <td width="145" align="center" bgcolor="#FFFFFF"  class="STYLE1">数量</td>
            <td width="145" align="center" bgcolor="#FFFFFF"  class="STYLE1">金额</td>
 </tr>&#39;;
foreach($name as $key=>$value){  //以book数组做循环,输出键和值
     echo &#39;<tr>
            <td height="25" align="center" bgcolor="#FFFFFF" class="STYLE2">&#39;.$value.&#39;</td>
            <td align="center" bgcolor="#FFFFFF" class="STYLE2">&#39;.$price[$key].&#39;</td>    
            <td align="center" bgcolor="#FFFFFF" class="STYLE2">&#39;.$counts[$key].&#39;</td>
            <td align="center" bgcolor="#FFFFFF" class="STYLE2">&#39;.$counts[$key]*$price[$key].&#39;</td>
</tr>&#39;;
}
echo &#39;</table>&#39;;
?>
</body>
</html>
Copy after login

3 Running result

foreach loop statement in PHP

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template