Cycle When you write code, you often need to make the same code block run many times. You can use loop statements in your code to accomplish this task.
In PHP, we can use the following loop statement:
While Loops through code blocks as long as the specified condition is true Do...while Executes the code block first, and then repeats the loop when the specified condition is set up For The number of times a code block is specified by looping foreach Loops the code block while statement based on each element in the array The while statement repeats the code block as long as the specified condition is set.
Syntax while (condition) code to is executed; example The following example demonstrates a loop that, as long as the variable i is less than or equal to 5, the code loops through. Each time the loop is cycled, the variable increments by 1:
<html> <body>
<?php $i = 1; while ($i <=5) { echo "The number is". $i. "<br/>"; $i + +; } ?>
</body> </html>do...while statement The Do...while statement executes the code at least once-then, as long as the condition is set, the loop repeats.
Syntax Do { code to is executed; } while (condition); Example The following example sums up the value of I and then, as long as I is less than 5, it continues to accumulate:
<html> <body>
<?php $i = 0; Do { $i + +; echo "The number is". $i. "<br/>"; } while ($i <5); ?>
</body> </html>for statement You can use a For statement if you have determined how many times the code block has been repeatedly executed.
Syntax for (initialization; condition; increment) { code to is executed; } Note: The For statement has three parameters. The first parameter initializes the variable, the second parameter holds the condition, and the third parameter contains the increment required to perform the loop. If you include multiple variables in the initialization or increment parameter, you need to separate them with commas. The condition must evaluate to TRUE or false.
Example The following example displays the text "Hello world!" 5 times:
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.