In php, PHP loops include while, do while, for, foreach, each and other commonly used PHP loop statements. Let me summarize some of my notes when learning loops.
Loops in PHP mainly allow users to execute the same block of code a specified number of times.
There are four main types of PHP loops: while, do...while, for, foreach. Below we explain the usage of each loop separately.
while statement:
As long as the specified condition is true, the code block will be executed in a loop.
Format:
while(expr)
{
Statement;
}
Semantics: First judge expr, if the expression expr is false, end; if the expression expr is true, execute the statement statement, and judge expr again after the execution is completed. If the expression expr is still true, continue to execute the statement statement; until The expression expr is false and ends.
Example:
The code is as follows | Copy code | ||||
echo $i; $i++; } ?>
|
do…while statement:
First execute the code block once, then repeat the loop when the specified condition is true.
Format:
do{
代码如下 | 复制代码 |
$i=6; |
while(expr) semantics: First execute the statement statement once, and then judge expr. If the expression expr is false, it ends; if the expression expr is true, continue to execute the statement statement in a loop, and judge expr again after the execution. If If the expression expr is still true, the statement statement continues to be executed; until the expression expr is false, it ends.
Note: The difference between it and while is that do...while executes the statement once without any judgment for the first time, and then judges whether the condition is true. It should be noted here that the others are the same as while. Example:
The code is as follows | Copy code |
$i=6; do
{
?> |
代码如下 | 复制代码 |
for ($i=1; $i<=5; $i++) |
The code is as follows | Copy code |
for ($i=1; $i<=5; $i++)<🎜>
{<🎜>
echo "Hello World! "; } ?> |
foreach statement: The foreach statement is used to loop through an array.
Every time the loop is executed, the value of the current array element will be assigned to the value variable (the array pointer will move one by one) – and so on.
Grammar
foreach (array as value)
{
Code to be executed;
}
Example
The following example demonstrates a loop that can output the values of a given array:
The code is as follows
|
Copy code
|
||||
$arr=array("one", "two", "three"); foreach ($arr as $value) { echo "Value: " . $value . " "; |
}
http://www.bkjia.com/PHPjc/628654.html