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:
<html>
<body>
<?php
For ($i =1 $i <=5; $i + +)
{
echo "Hello world!<br/>";
}
?>
</body>
</html>foreach statement
The foreach statement is used to iterate through the array.
For Each loop, the value of the current array element is assigned to the value variable (the array pointer moves one by one)-and so on.
Syntax
foreach (array as value)
{
code to is executed;
}
Example
The following example demonstrates a loop that can output the value of a given array:
<html>
<body>
<?php
$arr =array ("One", "nonblank", "three");
foreach ($arr as $value)
{
echo "Value:". $value. "<br/>";
}
?>
</body>
</html>