Loop

Loops

Loop is used to execute a statement or a block of statements, multiple times until and unless a specific condition is met.

php Loops through a block of code a specified number of times.

PHP supports following four loop types.

1.For Loop

The for loop is used when you know in advance that how many times you want to execute a statement or a block of statements.

syntax

for (init counter; test counter; increment counter) {
code to be executed for each iteration;
}

Example

<?php
$a=2;
for ($a = 2; $a<= 10; $a++) {
echo "The number is: $a
";
} ?>

Output

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

2.while loop

PHP loops through a block of code if and as long as a specified condition is true.If the test expression is true then the code block will be executed.

syntax

while (if the condition is true) {
// code is executed
}

Example

<?php
// PHP code to illustrate while loops
$num = 3;
while ($num < 15) {
$num += 2;
echo $num, "\n";
}
?>

Output

5 7 9 11 13 15

3.Do while loop

In do while loop block of code executed once and then condition is evaluated.Therefore, a statement is executed at least once on using the do…while loop.

Syntax

do {
//code is executed
} while
(if condition is true);

Example

<?php
$i = 3;
do{
$i++;
echo "The number is " . $i . "<br>";
}
while($i <= 10);
?>
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
The number is 11

4.foreach loop

foreach loop is used to iterate over arrays.It is used to loop through each key/value pair in an array.

Syntax

foreach ($array as $value)
{
code to be executed;
}

Example

<?php
$fruits = array("grapes", "guava", "mango");
foreach ($fruits as $value) {
echo "$value <br>";
}
?>

Output

grapes
guava
mango