Home >Backend Development >PHP Tutorial >Comparison of two usages of PHP's foreach()_PHP Tutorial

Comparison of two usages of PHP's foreach()_PHP Tutorial

WBOY
WBOYOriginal
2016-07-15 13:28:36726browse

There are two ways to use PHP’s foreach():

The first way to use PHP’s 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>

The array_name here is the name of the array you want to traverse. In each loop, the value of the current element of the array_name array is assigned to $value, And the subscript inside the array moves down one step, that is, the next loop will return to get the next element.

The second usage of PHP's 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>

The difference between PHP's foreach() here and the first method is that there is an extra $key, that is, in addition to In addition to the value of the current element being assigned to $value, the key value of the current element will also be assigned to the variable $key in each loop. The key value can be a subscript value or a string. For example, "0" in book[0]=1, "id" in book[id]="001".


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/446434.htmlTechArticlePHP’s foreach() has two usages: PHP’s foreach() first usage: foreach(array_nameas$ value) { statement; } The array_name here is the name of the array you want to traverse. In each loop, ar...
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