Home >Backend Development >PHP Tutorial >Comparison of two usages of PHP's foreach()_PHP Tutorial
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".