A Loop is an Iterative Control Structure that involves
executing the same number of code a number of times until a certain condition
is met. The basic idea behind a loop is to automate the repetitive
tasks within a program to save the time and effort. PHP supports four different
types of loops.
PHP supports four types of looping techniques
- for loop
- while loop
- do-while loop
- foreach loop
1. for loop: This type of loops is used when
the user knows in advance, how many times the block needs to execute. These
type of loops are also known as entry-controlled loops. There are three main
parameters to the code –
Syntax –
<?php
for(initialize;
condition; increment)
{
//Code to be executed
}
?>
|
- “Initialization” - Usually an integer, it is used to set the counter’s
initial value.
- “Condition” - We have to test the condition. If the condition
evaluates to true then we will execute the body of loop and go to update
expression otherwise we will exit from for loop.
- “Increment” - After executing loop body this expression increments /
decrements the loop variable by some value.
<?php
for($num=1;
$num<=10; $num+=2)
{
echo “$num \n”;
}
?>
|
Output –
1
3 5 7 9 |
2. while loop - The while loop is also an entry
control loop. The while statement will loops through a block of code until the condition
in the while statement evaluate to true.
Syntax –
<?php
While(condition)
{
//Code
to be executed
}
?>
|
Example –
<?php
$number
= 1;
while($number < 10)
{
$number+=2;
echo $number.”<br>”;
}
?>
|
Output –
3
5 7 9 11 |
3. do while 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.
Syntax –
<?php
do{
//Code to be executed
}
while(condition)
?>
|
Example –
<?php
$number = 1;
do
{
$number+=2;
echo
$number."<br>";
}while ($number < 10);
?>
|
4. foreach loop - The php foreach loop is
used to iterate through array values. For every counter of loop, an array
element is assigned and the next counter is shifted to the next element.
Syntax –
<?php
foreach($array_variable as $array_value)
{
//Code
to be executed
}
?>
|
Example -
<?php
$arr =
array(100, 200, 300, 400, 500, 600);
foreach($arr as $val)
{
echo
$val.”<br>”;
}
$arr =
array(“Cyber”,”Teak”,”Website”);
foreach($arr as $val)
{
echo
$val.”<br>”;
}
?>
|
Output –
100
200 300 400 500 600 Cyber Teak Website |
0 Comments