Loops in PHP
Loops in PHP
- Loops are used to execute the same block of code again and again, as long as a
certain condition is true.
- This helps the user to save both time and effort of writing the same code
multiple times.
1. while loop
2. do-while loop
3. for loop
4. foreach loop
Syntax:
while (condition)
{
// code to be executed
}
<html>
<body>
<?php
$i = 1;
?>
</body>
</html>
Output:
12345678910
- This is an exit control loop which means that it first enters the loop, executes
the statements, and then checks the condition.
- Therefore, a statement is executed at least once on using the do…while loop.
do
{
//code to be executed
} while (condition);
Example:
<html>
<body>
<?php
$i = 1;
do
{
echo $i;
$i++;
} while ($i < 11);
?>
</body>
</html>
Output:
12345678910
3. for loop:
Syntax:
Example:
<html>
<body>
<?php
?>
</body>
</html>
Ouput:
The number is: 0
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
4. foreach loop:
Syntax:
Example:
<html>
<body>
<?php
</body>
</html>
Output:
red
green
blue
yellow
- With the break statement we can stop the loop even if the condition is still
true:
<html>
<body>
<?php
$i = 1;
$i++;
}
?>
</body>
</html>
Output:
12
- With the continue statement we can stop the current iteration, and continue with
the next:
<html>
<body>
<?php
$i = 0;
</body>
</html>
Output:
12456