📅  最后修改于: 2020-09-28 01:48:54             🧑  作者: Mango
PHP的do-while循环可用于遍历phpwhile循环之类的代码集。确保PHP的do-while循环至少运行一次。
PHPdo-while循环用于多次执行程序的代码集。如果您必须至少执行一次循环并且迭代次数甚至不是固定的,则建议使用do-while循环。
它总是至少执行一次代码,因为执行代码后会检查条件。
除了条件检查外,do-while循环与while循环非常相似。两个循环之间的主要区别在于,while循环在开始时检查条件,而do-while循环在循环结束时检查条件。
do{
//code to be executed
}while(condition);
";
$n++;
}while($n<=10);
?>
输出:
1 2 3 4 5 6 7 8 9 10
使用分号终止do-while循环。如果在do-while循环后不使用分号,则必须在do-while循环后程序中不应包含任何其他语句。在这种情况下,它不会产生任何错误。
";
$x++;
} while ($x < 10);
?>
输出:
Welcome to javatpoint! Welcome to javatpoint! Welcome to javatpoint! Welcome to javatpoint! Welcome to javatpoint!
以下示例将使$x的值至少增加一次。因为给定条件为假。
";
$x++;
} while ($x > 10);
echo $x;
?>
输出:
1 is not greater than 10. 2
while Loop | do-while loop |
---|---|
The while loop is also named as entry control loop. | The do-while loop is also named as exit control loop. |
The body of the loop does not execute if the condition is false. | The body of the loop executes at least once, even if the condition is false. |
Condition checks first, and then block of statements executes. | Block of statements executes first and then condition checks. |
This loop does not use a semicolon to terminate the loop. | Do-while loop use semicolon to terminate the loop. |