For Loop in PHP. Loops in PHP are used to execute a task continuously. For Loop in PHP has different forms. While loop and for loop performs a block of the program, that is based on a condition. When it is identified before that a selective block of code should run this number of times state 10 times we use for loop.
PHP for loop can be used to traverse the set of programs for the defined number of times. It can be used if the number of repetitions is known unless use while loop. This means for the loop is used when you already know how many times you want to run a block of the program.
A for loop holds expressions succeeded by a semicolon; the below is the syntax.
for(initialization; condition; increment++ / decrement--) { ///for loop body }
Initialization: is the naming and assigning or initializing the value of the variable used, it operates an integer value.
Condition: for the loop to work this condition is held first and assessed if it is true only then the loop runs more.
Increment/Decrement: this increases++/decreases– the value of the variable for the loop to iterate.
How For Loop Works?
First, the initialization of variables is assessed. Second, with each repetition of loop condition is checked, if it is true, the program will continue, and the block of code will execute. And if the condition is not true, indicating false then the loop ends, there itself without the block of program or statements to be run. Last, the increase and decrease in the initialized variable are done after the program execution of the statements mentioned.
Examples of For Loop in PHP
Here are the two examples are given below
Example #1
Learn in the below program, the value of j is initialized to 0, therefore, the $j variable is printed using echo, we get the values starting with 0 and continue to print until 5 as the condition is to print till value 5.
<?php for($j=0; $j<=5;$j++) { echo '<br>'; echo 'Value of J is '. $j; } ?>
Example #2
In the below program, the value of J is initialized to 0, therefore, the $J variable is printed using echo statement, we see the values beginning with 0 and continue to print till 5 as the condition is to print till value 5.
Here the initializing of the variable J is not in the for loop but outside the for a loop at the beginning of the program.
<?php $J=0; for(; $J<=5;$J++) { echo '<br>'; echo 'Value of J is '.$J; } ?>
Conclusion
In this article, we studied for loop, the syntax of the flow chart, how the loop runs in PHP, and related loops like the foreach loop. We also discovered how the loop repeats frequently and also how it repeats through arrays. Hope this article is found to be informational and helpful.