PHP like any other programming language makes use of loops to perform particular task repeatedly. You can use loops to perform tasks that are supposed to be executed if certain condition is met upto particular period. Like this there are many ways to use loops while programming with php. In this tutorial we’re going to take a look at ways with which we can use loops in php.
Loops always check for the particular condition before executing particular task. If the condition is true or false, it’ll generate the output for the loop.
While Loop
Let’s start learning with ‘while’ loop first. Check the basic syntax of the while loop:
Code
<?php while(condition) { } ?>
You’ve to place some condition in order to execute while loop. If your condition evalutes to true, the loop will execute or lese it’ll not.
<?php $i=1; while ($i<=10) { echo $i; echo '<br/>'; $i++; } ?>
For Loop
For loop allows you to have control over initiation, condition and increment in the same line. Like while loop it also processes a block of code until a statement becomes false.
Syntax Code:
<?php for (condition) { } ?>
In this code our condition statement contains – initiation, condition and increment. You can skip increment if you want to use it inside the block of code. Either way with increment is fine with for loop. Check the modification in code made for – “for loop”.
<?php for($=1;$i<=10;$i++) { echo $i; echo '<br/>'; $i++; } ?>
FOREACH Loop
A foreach loop is used when you’re dealing with arrays. It executes a block of code as long as loop uses all the values of arrays specified in the condition are used. Once those values are used then loop ends. So there is no need to explicitly add the increment for the arrays.
Syntax
<?php $i=array(); foreach($i as $j) { } ?>
In this loop, we’re creating an array to be used foreach loop. This array specifies a particular set of values upto which the loop will execute.
<?php $i=array(1,2,3,4,5); foreach($i as $k) { echo $k; echo '<br/>'; } ?>
As you can see in the output, this loop executes till all the values in array are used. Once used you can see that loop ends.
These three are the types of loops that you’re going to use while programming in php. Hope this tutorial helps to you and if you have any suggestion or feedback on these tutorials, feel free to let us know.