PHP Loops:
- 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.
PHP supports four types of looping techniques;
1. while loop
2. do-while loop
3. for loop
4. foreach loop
1. while loop: Entry Controlled Loop
Syntax:
while (condition)
{
// code to be executed
}
<html>
<body>
<?php
$i = 1;
while ($i < 11)
{
echo $i;
$i++;
}
?>
</body>
</html>
Output:
12345678910
2. do-while loop: Exit controlled loop
- 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:
- These type of loops are also known as entry-controlled loops.
- There are three main parameters to the code, namely the initialization, the test
condition and the counter.
Syntax:
for (initialization expression; test condition; increment/decrement)
{
// code to be executed
}
Example:
<html>
<body>
<?php
for ($x = 0; $x <= 10; $x++)
{
echo "The number is: $x <br>";
}
?>
</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:
- This loop is used to iterate over arrays.
- For every counter of loop, an array element is assigned and the next counter is
shifted to the next element.
Syntax:
foreach (array_name as variable)
{
//code to be executed
}
Example:
<html>
<body>
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $x)
{
echo "$x <br>";
}
?>
</body>
</html>
Output:
red
green
blue
yellow
The jumping statements:
1. break
2. continue
The break Statement
- With the break statement we can stop the loop even if the condition is still
true:
<html>
<body>
<?php
$i = 1;
while ($i < 11)
{
if ($i == 3)
break;
echo $i;
$i++;
}
?>
</body>
</html>
Output:
12
The continue Statement
- With the continue statement we can stop the current iteration, and continue with
the next:
<html>
<body>
<?php
$i = 0;
while ($i < 6)
{
$i++;
if ($i == 3)
continue;
echo $i;
}
?>
</body>
</html>
Output:
12456