Loop statement for beginners to PHP
for loop
<?php header("Content-type: text/html; charset=utf-8");//設(shè)置編碼 //計(jì)算1到10之和 $sum = 0 ; //定義一個(gè)變量 初始值為0 for($i=1;$i<=10;$i++){ //進(jìn)入循環(huán),當(dāng)$i是1時(shí),滿足條件,執(zhí)行$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 循環(huán) 1到10 之和 $sum = 0; $i = 1; while($i<=10){ $sum = $sum + $i; $i++; //如果沒有$i++ 那么$i的值就不會(huì)發(fā)生變化,這樣就會(huì)一直循環(huán) } 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 循環(huán) 寫出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 循環(huán)中break 與continue 的區(qū)別
//當(dāng)使用break的時(shí)候,$i的值是5的時(shí)候就跳出循環(huán)體
//使用continue的時(shí)候,只有$i是5的時(shí)候跳出循環(huán)
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 循環(huán) $arr = array('one','two','three','four','five'); //創(chuàng)建一個(gè)數(shù)組,里面有5個(gè)元素 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