PHP Loop-For Loop
Loop executes the number of times specified by the code block, or the loop executes the code block when the specified condition is true.
For loop
The For loop is used in cases where you know in advance how many times the script needs to run.
Grammar
for (initial value; condition; increment) { the code to execute;}
Parameters:
- Initial value : The primary is to initialize a variable value that sets a counter (but can be any code that is executed once at the beginning of the loop).
- condition : The throttling condition of the loop execution. If true, the loop continues. If FALSE, the loop ends.
- increment : Mainly used for incrementing the counter (but can be any code executed at the end of the loop).
Note: The above initial and increment parameters can be empty, or there are multiple expressions (separated by commas).
Instance
The following example defines a loop with an initial value of I=1. As long as the variable i is less than or equal to 5, the loop continues to run. Each time the loop is run, the variable i increments by 1:
Instance
for ($i$i$iecho$i . "<br>"; }?>
Output:
number is 1 number are 2 number is 3 number is 4< c15> number is 5
foreach Loop
A foreach loop is used to iterate through an array.
Grammar
foreach ($arrayas$value) { to execute code;}
For Each loop, the value of the current array element is assigned to the $value variable (the array pointer moves one at a time), and you will see the next value in the array when the next loop is made.
Instance
The following example shows a loop that outputs the value of a given array:
Instance
$x=arrayforeach ($xas$valueecho$value . "<br>"; }?>
Output:
Onetwothree
PHP Quick Start learning -14 (Php-for Loop)