像任何其他语言一样, PHP中的循环用于多次执行一条语句或一段语句, 直到满足特定条件为止。这有助于用户节省多次编写同一代码的时间和精力。
PHP支持四种类型的循环技术。
- for循环
- while循环
- 循环执行
- foreach循环
现在让我们详细了解上述每个循环:
for循环
:当用户事先知道该块需要执行多少次时, 使用这种类型的循环。即, 迭代次数是事先已知的。这些类型的循环也称为入口控制循环。该代码有三个主要参数, 即初始化, 测试条件和计数器。
语法:
for (initialization expression; test condition; update expression) {
// code to be executed
}
在for循环中, 使用循环变量来控制循环。首先将此循环变量初始化为某个值, 然后检查此变量是否小于或大于计数器值。如果statement为true, 则执行循环主体, 并更新循环变量。重复步骤直到退出条件出现。
- 初始化表达式:在此表达式中, 我们必须将循环计数器初始化为某个值。例如:$ num = 1;
- 测试表达:在此表达式中, 我们必须测试条件。如果条件的计算结果为true, 则我们将执行循环的主体并更新表达式, 否则将退出for循环。例如:$ num <= 10;
- 更新表达:执行循环体后, 此表达式将循环变量增加/减少一些值。例如:$ num + = 2;
例子:
<?php
// code to illustrate for loop
for ( $num = 1; $num <= 10; $num += 2) {
echo "$num \n" ;
}
?>
输出如下:
1
3
5
7
9
流程图:
while循环
:while循环也是类似于for循环的入口控制循环, 即, 它首先在循环开始时检查条件, 如果条件为true, 则进入循环并执行语句块, 并一直执行到条件成立。
语法:
while (if the condition is true) {
// code is executed
}
例子:
<?php
// PHP code to illustrate while loops
$num = 2;
while ( $num < 12) {
$num += 2;
echo $num , "\n" ;
}
?>
输出如下:
4
6
8
10
12
流程图:
do-while循环执行
:这是一个退出控制循环, 这意味着它首先进入循环, 执行语句, 然后检查条件。因此, 使用do…while循环至少要执行一次语句。执行一次后, 只要条件成立, 程序就会执行。
语法:
do {
//code is executed
} while (if condition is true);
例子:
<?php
// PHP code to illustrate do...while loops
$num = 2;
do {
$num += 2;
echo $num , "\n" ;
} while ( $num < 12);
?>
输出如下:
4
6
8
10
12
该代码将显示while和do…while循环之间的区别。
<?php
// PHP code to illustrate the difference of two loops
$num = 2;
// In case of while
while ( $num != 2) {
echo "In case of while the code is skipped" ;
echo $num , "\n" ;
}
// In case of do...while
do {
$num ++;
echo "The do...while code is executed atleast once " ;
} while ( $num == 2);
?>
输出如下:
The code is executed at least once
流程图:
foreach循环
:此循环用于遍历数组。对于循环的每个计数器, 分配一个数组元素, 然后将下一个计数器移至下一个元素。
语法
foreach (array_element as value) {
//code to be executed
}
例子:
<?php
$arr = array (10, 20, 30, 40, 50, 60);
foreach ( $arr as $val ) {
echo "$val \n" ;
}
$arr = array ( "Ram" , "Laxman" , "Sita" );
foreach ( $arr as $val ) {
echo "$val \n" ;
}
?>
输出如下:
10
20
30
40
50
60
Ram
Laxman
Sita
如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请写评论。
更多PHP开发相关内容请参考:lsbin - IT开发技术:https://www.lsbin.com/
查看以下更多PHP相关的内容: