📄 control-structures.foreach.html
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html> <head> <title>foreach</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> </head> <body><div style="text-align: center;"> <div class="prev" style="text-align: left; float: left;"><a href="control-structures.for.html">for</a></div> <div class="next" style="text-align: right; float: right;"><a href="control-structures.break.html">break</a></div> <div class="up"><a href="language.control-structures.html">Control Structures</a></div> <div class="home"><a href="index.html">PHP Manual</a></div></div><hr /><div id="control-structures.foreach" class="sect1"> <h2 class="title"><i>foreach</i></h2> <p class="para"> PHP 4 introduced a <i>foreach</i> construct, much like Perl and some other languages. This simply gives an easy way to iterate over arrays. <i>foreach</i> works only on arrays, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes; the second is a minor but useful extension of the first: <div class="informalexample"> <div class="example-contents"><div class="cdata"><pre>foreach (array_expression as $value) statementforeach (array_expression as $key => $value) statement</pre></div> </div> </div> </p> <p class="simpara"> The first form loops over the array given by <i>array_expression</i>. On each loop, the value of the current element is assigned to <i>$value</i> and the internal array pointer is advanced by one (so on the next loop, you'll be looking at the next element). </p> <p class="simpara"> The second form does the same thing, except that the current element's key will be assigned to the variable <i>$key</i> on each loop. </p> <p class="simpara"> As of PHP 5, it is possible to <a href="language.oop5.iterations.html" class="link">iterate objects</a> too. </p> <p class="para"> <blockquote><p><b class="note">Note</b>: When <i>foreach</i> first starts executing, the internal array pointer is automatically reset to the first element of the array. This means that you do not need to call <a href="function.reset.html" class="function">reset()</a> before a <i>foreach</i> loop. <br /> </p></blockquote> </p> <p class="para"> <blockquote><p><b class="note">Note</b>: Unless the array is <a href="language.references.html" class="link">referenced</a>, <i>foreach</i> operates on a copy of the specified array and not the array itself. <i>foreach</i> has some side effects on the array pointer. Don't rely on the array pointer during or after the foreach without resetting it. <br /> </p></blockquote> </p> <p class="para"> As of PHP 5, you can easily modify array's elements by preceding
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -