search
Homephp教程php手册php中几种常用的循环结构

php中几种常用的循环结构

Jun 06, 2016 pm 08:00 PM
phpseveral kindscycleusestructure

php中几种常用的循环结构 while 一般使用方法: $i=1;while($i5){ echo The number is . $i . br /; $i++;} 上面的例子示范了一个循环,只要变量 i 小于 5,代码就会一直循环执行下去。循环每循环一次,变量就会递增 1。 while括号中还可以加方法或恒等式,只

php中几种常用的循环结构

while

一般使用方法:

$i=1;
while($i";
  $i++;

}
上面的例子示范了一个循环,只要变量 i 小于 5,代码就会一直循环执行下去。循环每循环一次,变量就会递增 1。

while括号中还可以加方法或恒等式,只要括号中的条件一直为真,循环就会一直循环下去

$user='rose';
while(!checkname($user)){
	
	echo "the user is exist";
	
	$user.='abc';
}

上面的例子是模拟用户自动注册时,检查用户名是否已经被使用的情况。checkname是检查用户名的一个方法。

适用场景:判断用户名是否存在,一般数据库查询生成表格等


do...while 

$i=0;
do
  {
  $i++;
  echo "The number is " . $i . "<br>";
  }
while ($i
<p>do-while循环和while循环非常相似,其区别只是在于do-while保证必须执行一次,而while在表达式不成立时则可能不做任何操作。<br>
</p>
<p>do...while 语句会至少执行一次代码 - 然后,只要条件成立,就会重复进行循环<br>
</p>
<p>上面的例子将对 i 的值进行一次累加,然后,只要 i 小于 5 的条件成立,就会继续累加下去. </p>
<p>从结果来看,do...while循环结构 比 while结构 ,多循环一次。</p>
<p>原因是while 是先判断 再执行, do...while是先执行再判断</p>
<p><strong>适用场景</strong>:至少要执行一次的程序</p>
<p><strong><span><br>
</span></strong></p>
<p><strong><span><span>for</span></span></strong></p>

<pre class="brush:php;toolbar:false">FOR ($i = 0; $i "; 
} 
这里执行3次 

for 和 while 差不多,只要表达式不成立时,不做任何操作

上面的例子等同于

$i=0;
while($i ";
$i++;
}
如果硬要做个比较的话,我感觉while的适用范围会比for好,for一般做一些数学上的运算




Statement
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),