Like any other programming language, we can define all type of loops in php, In this tutorial you will learn how to write loops in php.
What is Loop in Php?
Loop is a Control Structure that helps executing any code or logic
number of times until a certain condition is satisfied.
Loop will be very useful in following situation
Here you learn all type of Loops in Php with examples
For loop syntax is same as in other programming language.
<?php for ($x = 1; $x <= 10; $x++) { echo "The number is: $x <br>"; } ?>
Result of the above for loop , loop runs till value of X is less or equal to 10
The number is: 1 The number is: 2 The number is: 3 The number is: 4 The number is: 5 The number is: 6 The number is: 7 The number is: 8 The number is: 9 The number is: 10
Foreach loop will continue till the end of collection object or array
ForEach loop Syntax<?php $colors = array("Java", ".Net", "SQL", "LINQ","PHP", "JQuery"); foreach ($colors as $value) { echo "$value"; } ?>
If condition is satisfied then while loop is executed
While loop Syntax<?php while (condition){ block of code to be executed; } Example $i = 0; while ($i < 5){ echo $i + 1 . "<br>"; $i++; } ?>
Do loop start executing, then when condition is satisfied then exit the loop
Do While loop Syntax<?php do{ block of code to be executed } Example $i = 10; do{ echo "$i is"." <br>"; } while($i < 10); ?>
Loop structure is almost same in every programming language, may be there are some minor syntax difference, if interested, look at loops example below in other programming language.