Looping statements in PHPLooping statements are used to perform an action to a number of times. There are four looping statements in PHP-
1.while statement
2. do...while statement
3. for loop
4.foreach loop
while statementThe while statement is used to repeatedly execute a block of statements as long as a specified condition is true. The syntax is as follows-
CODE
while (condition)
{
code to be executed;
}
Example:while statement
[code]
<?php
$i=0;
while($i<5)
{
print "Hello World!"."<br/>";
$i++;
}
?>
Output:
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
do...while statementLike while statement, do...while statement is another looping statements used in PHP. The basic difference with while statement is that, in case of while statement, the condition is checked at the begining and if the condiotion is false, the statement block is never executed. On the other hand, in case of do...while statement, the condition is checked at the end of the loop and the statement block is executed for at least once even the condition is initially false. The structure of do...while loop is as follows-
CODE
do
{
code to be executed;
}
while(condition);
Example:do...while statement
CODE
<?php
$i=0;
do
{
$i++;
print $i.”<br/>”;
}
while ($i<5);
?>
Output:
1
2
3
4
5
for loopGenerally while loops are used when the number of passes of the loop is not known. But, when the number of passes is known, it is better to use another looping statement which is for loop. Here is the general syntax of for loop-
CODE
for (initialization; condition; increment)
{
code to be executed;
}
Example:for loop
CODE
<?php
for ($i=0; $i<5; $i++)
{
print $i.”<br/>”;
}
?>
Output:
0
1
2
3
4
foreach loopPHP provides another looping statement which is used to loop through arrays. The structure of foreach loop is as follows-
CODE
foreach (array as value)
{
code to be executed;
}
Example:foreach loop
CODE
<?php
$a=array("atik"=>20,"pervej"=>21,"jahid"=>18);
foreach($a as $name=>$age)
{
print "Name:".$name." Age:".$age."<br/>";
}
?>
Output:
Name:atik Age:20
Name:pervej Age:21
Name:jahid Age:18