PHP For Loop
Loop through a block of code a specified number of times, or when a specified condition is true.
for loop
The for loop is used when you know in advance the number of times the script needs to run.
Syntax
{
Code to be executed;
}
Parameters:
Initial value: Mainly initializes a variable value, used to set a counter (but it can be any Code that is executed once at the beginning of the loop).
Conditions: Restrictions on loop execution. If TRUE, the loop continues. If FALSE, the loop ends.
Increment: Mainly used to increment the counter (but can be any code that is executed at the end of the loop).
Note: The above initial value and increment parameters can be empty or have multiple expressions (Separate with commas).
Example
The following example defines a loop with an initial value of i=1. The loop will continue to run as long as variable i is less than or equal to 5. Each time the loop runs, the variable i will be incremented by 1:
<html> <body> <?php for ($i=1; $i<=5; $i++) { echo "The number is " . $i . "<br>"; } ?> </body> </html>
Output:
The number is 1 The number is 2 The number is 3 The number is 4 The number is 5
foreach loop
The foreach loop is used to traverse the array.
Syntax
{
Code to be executed;
}
Every time the loop is performed, the value of the current array element will be assigned to the $value variable (the array pointer will be moved one by one). When the next loop is performed, you will see the the next value.
Example
The following example demonstrates a loop that outputs the values of a given array:
<html> <body> <?php $x=array("one","two","three"); foreach ($x as $value) { echo $value . "<br>"; } ?> </body> </html>output:
one two three