Correct application of PHP foreach loop_PHP tutorial

WBOY
Release: 2016-07-15 13:33:14
Original
900 people have browsed it

  1. < html> 
  2. < body> 
  3. < ?php  
  4. $arr=array("one", "two", "three");  
  5. foreach ($arr as $value)  
  6. {  
  7. echo "Value: " . $value . "< br />";  
  8. }  
  9. ?> 
  10. < /body> 
  11. < /html> 

在这个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>
Copy after login

注解:通过PHP foreach循环我们把数组$sounds的键赋于变量$animal,把数组的值赋值给$sound,这样我们就可以方便的访问数组每一个“键值对”(key-value)了。


www.bkjia.comtruehttp://www.bkjia.com/PHPjc/446070.htmlTechArticlehtml body ?php $ arr = array (one,two,three); foreach($arras$value) { echoValue:.$value. br / ; } ? /body /html 在这个PHP foreach循环的例子里,我们创建了$arr数组,里...
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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template