Home > php教程 > php手册 > PHP的foreach()的两种用法评比

PHP的foreach()的两种用法评比

WBOY
Release: 2016-06-13 11:05:35
Original
1124 people have browsed it

PHP的foreach()有两种用法:

PHP的foreach()第一种用法:

<ol class="dp-xml">
<li class="alt"><span><span>foreach(array_nameas$value)  </span></span></li>
<li class=""><span>{  </span></li>
<li class="alt"><span>statement;  </span></li>
<li class=""><span>}  </span></li>
</ol>
Copy after login

这里的array_name是你要遍历的数组名,每次循环中,array_name数组的当前元素的值被赋给$value,并且数组内部的下标向下移一步,也就是下次循环回得到下一个元素。

PHP的foreach()第二种用法:

<ol class="dp-xml">
<li class="alt"><span><span>foreach(array_nameas$</span><span class="attribute"><font color="#ff0000">key</font></span><span>=</span><span class="tag"><strong><font color="#006699">></font></strong></span><span>$value)  </span></span></li>
<li class=""><span>{  </span></li>
<li class="alt"><span>statement;  </span></li>
<li class=""><span>}  </span></li>
</ol>
Copy after login

这里的PHP的foreach()跟第一种方法的区别就是多了个$key,也就是除了把当前元素的值赋给$value外,当前元素的键值也会在每次循环中被赋给变量$key。键值可以是下标值,也可以是字符串。比如book[0]=1中的“0”,book[id]="001"中的“id”。


Related labels:
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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template