admin 发表于 2023-2-16 18:54:41

PHP 循环 - While 循环

<div id="article_content" class="article_content clearfix">
      <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/kdoc_html_views-1a98987dfd.css">
      <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/ck_htmledit_views-6e43165c0a.css">
                <div id="content_views" class="htmledit_views">
                  <p>循环执行代码块指定的次数&#xff0c;或者当指定的条件为真时循环执行代码块。</p>
<hr>
<h2>PHP 循环</h2>
<p>在您编写代码时&#xff0c;您经常需要让相同的代码块一次又一次地重复运行。我们可以在代码中使用循环语句来完成这个任务。</p>
<p>在 PHP 中&#xff0c;提供了下列循环语句&#xff1a;</p>
<ul><li><strong>while </strong>- 只要指定的条件成立&#xff0c;则循环执行代码块</li><li><strong>do...while</strong> - 首先执行一次代码块&#xff0c;然后在指定的条件成立时重复这个循环</li><li><strong>for </strong>- 循环执行代码块指定的次数</li><li><strong>foreach </strong>- 根据数组中每个元素来循环代码块</li></ul>
<hr>
<h2>while 循环</h2>
<p>while 循环将重复执行代码块&#xff0c;直到指定的条件不成立。</p>
<h3>语法</h3>
<pre>while (条件)
{
    要执行的代码;
}</pre>
<h3>实例</h3>
<p>下面的实例首先设置变量 <em>i</em> 的值为 1 ($i&#61;1;)。</p>
<p>然后&#xff0c;只要 <em>i</em> 小于或者等于 5&#xff0c;while 循环将继续运行。循环每运行一次&#xff0c;<em>i</em> 就会递增 1&#xff1a;</p>
<pre><html>
<body>

<?php
$i&#61;1;
while($i<&#61;5)
{
    echo &#34;The number is &#34; . $i . &#34;<br>&#34;;
    $i&#43;&#43;;
}
?>

</body>
</html></pre>
<p>输出&#xff1a;</p>
<p>The number is 1<br> The number is 2<br> The number is 3<br> The number is 4<br> The number is 5</p>
<p></p>
<hr>
<h2>do...while 语句</h2>
<p>do...while 语句会至少执行一次代码&#xff0c;然后检查条件&#xff0c;只要条件成立&#xff0c;就会重复进行循环。</p>
<h3>语法</h3>
<pre>do
{
    要执行的代码;
}
while (条件);</pre>
<h3>实例</h3>
<p>下面的实例首先设置变量 <em>i</em> 的值为 1 ($i&#61;1;)。</p>
<p>然后&#xff0c;开始 do...while 循环。循环将变量 <em>i</em> 的值递增 1&#xff0c;然后输出。先检查条件&#xff08;<em>i</em> 小于或者等于 5&#xff09;&#xff0c;只要 <em>i</em> 小于或者等于 5&#xff0c;循环将继续运行&#xff1a;</p>
<pre><html>
<body>

<?php
$i&#61;1;
do
{
    $i&#43;&#43;;
    echo &#34;The number is &#34; . $i . &#34;<br>&#34;;
}
while ($i<&#61;5);
?>

</body>
</html></pre>
<p>输出&#xff1a;</p>
<p>The number is 2<br> The number is 3<br> The number is 4<br> The number is 5<br> The number is 6</p>
<p>for 循环和 foreach 循环将在下一章进行讲解。</p>
                </div>
      </div>
      <div id="treeSkill"></div>
页: [1]
查看完整版本: PHP 循环 - While 循环