Home > Article > Backend Development > PHP loop learning 2: How to use do-while loop statements
In the previous article "PHP Loop Learning 1: The use of while loop statements (detailed examples)", we learned about the while loop statement and introduced the function and use of the while loop statement through code examples. method. The following article will introduce to you a variant of the while loop statement - the do-while loop statement. Let's take a look at how to use the do-while loop statement. Let's learn together!
The do-while loop statement is a "until type
" loop statement. It first executes the "statement block" in the loop body once, and then performs the loop condition Judge, if true, continue the loop, if false, terminate the loop.
Therefore: Regardless of the result of the expression, the do-while loop statement will execute the "statement block" at least once. (Attached manual: PHP While Loop)
Features of the do-while loop statement: Execute the loop body first, and then determine whether the loop condition is true.
The general form of do-while loop is:
do{ 语句块; }while(表达式);//表达式为循环条件
Description:
and while Like loops, the calculation result of the "expression" in the do-while loop must be Boolean TRUE or FALSE. If it is a value of other types, it will be automatically converted to a Boolean value.
The semicolon
;
at the end of the do-while statement cannot be omitted (it must be present). It is part of the syntax of the do while loop.
Statement analysis:
First execute the "statement block" in the loop body once, and then determine the value of the "expression" , when the value of "expression" is true, return to re-execute the statement block in the loop body... This process will be repeated
until the value of the expression is false, jump out Loop, at this point the loop ends and the following statements are executed.
The flow chart of the do-while loop statement is as follows:
Example:
Still the example from the previous article: Calculate the value of 1 added to 100
<?php header("Content-type:text/html;charset=utf-8"); $i = 1; $sum=0; do { $sum += $i; $i++; } while ($i <= 100); echo '1 + 2 + 3 +...+ 99 + 100 = '. $sum; ?>
Output result:
1 + 2 + 3 +...+ 99 + 100 = 5050
Recommendation: 《PHP Interview Summary of questions (collection)》《php video tutorial》
The above is the detailed content of PHP loop learning 2: How to use do-while loop statements. For more information, please follow other related articles on the PHP Chinese website!