>  기사  >  백엔드 개발  >  PHP의 foreach 루프 문

PHP의 foreach 루프 문

巴扎黑
巴扎黑원래의
2016-12-28 17:41:131504검색

단일 구문

foreach(array_expression as $value)

문;

foreach(array_expression as $key=>$value)

구문;

foreach 문은 배열 array_expression을 순회합니다. 루프할 때마다 현재 배열의 값이 $value(또는 $key 및 $value)에 할당됩니다. 순회가 완료될 때까지 배열은 뒤로 이동합니다. foreach를 사용할 때 배열 포인터가 자동으로 재설정되므로 포인터 위치를 수동으로 설정할 필요가 없습니다.

두 가지 예

<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>

세 가지 실행 결과

PHP의 foreach 루프 문

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.