在这个PHP foreach循环的例子里,我们创建了$arr数组,里面的元素值是”one”,”two”,”three”,然后通过一个foreach循环来输出其数组的值。数组里面的值通过”as”存到变量value里,这样value就保存了数组arr的各个元素了。
在这里,我们所针对的是自动索引的数组,如果是关联数组呢?请看下面一种情况:
<ol class="dp-xml"> <li class="alt"><span><span>$</span><span class="attribute">sounds</span><span>=</span><span class="attribute-value">array</span><span>(”cow”=</span><span class="tag">></span><span>”moo”,”dog”<br>=</span><span class="tag">></span><span>”woof”,”pig”=</span><span class="tag">></span><span>”oink”,”duck”=</span><span class="tag">><br></span><span>”quack”); </span></span></li> <li> <span>foreach($sounds as $</span><span class="attribute">animal</span><span>=</span><span class="tag">></span><span>$sound) </span> </li> <li class="alt"><span>{ </span></li> <li><span>Print “And of that farm he had a <br>{$animal}”; </span></li> <li class="alt"><span>} </span></li> </ol>
注解:通过PHP foreach循环我们把数组$sounds的键赋于变量$animal,把数组的值赋值给$sound,这样我们就可以方便的访问数组每一个“键值对”(key-value)了。