Loop statement for beginners to PHP
for loop
<?php header("Content-type: text/html; charset=utf-8");//设置编码 //计算1到10之和 $sum = 0 ; //定义一个变量 初始值为0 for($i=1;$i<=10;$i++){ //进入循环,当$i是1时,满足条件,执行$i++ $sum = $sum + $i; } echo $sum; ?>
while loop
Format: while (condition){ Execution code;}Use the while loop to calculate the number between 1 and 10 And<?php //while 循环 1到10 之和 $sum = 0; $i = 1; while($i<=10){ $sum = $sum + $i; $i++; //如果没有$i++ 那么$i的值就不会发生变化,这样就会一直循环 } echo $sum; ?>
do....while loop
##Format: do{
Execution statement;
}while(condition);
Use do....while to realize the sum of 1 to 10
<?php //do......while 循环 写出1到10 之和 $sum = 0 ; $i = 1; do{ $sum = $sum +$i; $i++; }while($i<=10); echo $sum; ?>
Note:
No matter whether $i meets the condition or not , the loop body will be executed once. When i = 10, enter the loop body and execute $i++. At this time, the value of $i is 11 and then enter the conditional judgment. If the condition is not met, jump out of the loop<?php
//for 循环中break 与continue 的区别
//当使用break的时候,$i的值是5的时候就跳出循环体
//使用continue的时候,只有$i是5的时候跳出循环
for ($i=1;$i<=10;$i++){
if($i==5){
break;
//continue;
}
echo $i."</br>";
}
?>
The foreach loop is used to traverse the array.
Execution code;
}
<?php //foreach 循环 $arr = array('one','two','three','four','five'); //创建一个数组,里面有5个元素 foreach ($arr as $val) { echo $val."</br>"; } ?>
Note: Each cycle is performed. The values in the array will be assigned to the $val variable (the array pointer will move one by one). When you perform the next loop, you will see the next value in the array