当前位置: 首页 > 网络学院 > 服务端脚本教程 > PHP > PHP 循环
Looping statements in PHP are used to execute the same block of code a specified number of times.
PHP循环语句的作用是:对同一个代码块执行指定的次数。
Very often when you write code, you want the same block of code to run a number of times. You can use looping statements in your code to perform this.
在书写代码时,你经常会发现,某个代码快要被多次执行。如果出现了这种情况,你就可以通过循环语句来实现它。
In PHP we have the following looping statements:
PHP中的循环语句具体指令如下:
The while statement will execute a block of code if and as long as a condition is true.
While语句指定了循环语句执行的条件,只要条件为真[true],它就会执行相应的代码块。
while (条件) |
The following example demonstrates a loop that will continue to run as long as the variable i is less than, or equal to 5. i will increase by 1 each time the loop runs:
在下面的案例中,当变量i小于等于5时,循环语句将持续的执行;每执行一个循环,i的值自动加“1”。
<html> <?php </body> |
The do...while statement will execute a block of code at least once - it then will repeat the loop as long as a condition is true.
如果使用do...while语句,那么指定的代码块将至少被执行一次;当while后面的条件为真时,它将重复执行该指定的代码块:
do |
The following example will increment the value of i at least once, and it will continue incrementing the variable i as long as it has a value of less than 5:
下面的例子讲执行i的值至少一次;只要i的值小于5,这个代码段将被重复执行:
<html> <?php </body> |
The for statement is used when you know how many times you want to execute a statement or a list of statements.
For语句是用来设置循环语句的执行次数以及语句列表的。
for (初始值; 条件; 增值) |
Note: The for statement has three parameters. The first parameter initializes variables, the second parameter holds the condition, and the third parameter contains the increments required to implement the loop. If more than one variable is included in the initialization or the increment parameter, they should be separated by commas. The condition must evaluate to true or false.
注意:For语句中可以设置三个参数:第一个参数是变量的初始值(初始参数);第二个参数是循环执行的条件(条件参数);第三个参数设置了增量参数在执行一次循环需要自动增加的量(增量参数)。如果初始参数或增量参数不止一个时,它们之间需要用逗号“,”隔开。条件参数必须可以返回一个逻辑参数(即:真true/假false)。
The following example prints the text "Hello World!" five times:
下面这个案例输出“Hello World!”五次:
<html> <?php </body> |
The foreach statement is used to loop through arrays.
Foreach语句是用来对数组执行循环的。
For every loop, the value of the current array element is assigned to $value (and the array pointer is moved by one) - so on the next loop, you'll be looking at the next element.
对于每一个循环语句来说,当前的数组元素都被指派了一个值($value)——所以在下一个循环中,你将看到下一个元素。
foreach (数组 as 值) |
The following example demonstrates a loop that will print the values of the given array:
下面的案例将循环输出给定数组中的所有变量值:
<html> <?php foreach ($arr as $value) </body> |