PHP for-each and while Loops

on Thursday, November 8, 2012

for-each loop

Some of us have the question that why we use for-each when we have already for loop.
So that the answer is for-each loop is used for the array, but how?

Coming to the Syntax:
foreach($arrayname as $value)
{
// code for execution
}
EXAMPLE
$myname=array(“softfive”,”soft”)
foreach($myname as $value)
{
echo $value.” , “;
}
Output
Softfive , soft


WHILE Loops

Now coming to the while loop, many of us used the while loop. The syntax of while loop is same as other programming languages like C,C#,etc.

Syntax:

while(condition)
{
// code for execution
}
Note: In case of while when the condition is true then code executed.

Do-While loop

When we are talking about while loop it is common to come do-while loop.
Syntax:

do{
// code for execution
}while(condition);

EXAMPLE
$a=1;
while($a=5)
{
 ++$a;
echo $a.”<br />”;
}
Output
2
3
4
5
6
IMPORTANT =>
Many of us have the confusion that what is the difference between ‘while’ and ‘do-while’ loop
So the main difference is

 WHILE EXECUTED IF THE CONDITION IS TRUE whereas DO WHILE EXECUTED AT LEAST ONE TIME IF THE CONDITION IS FALSE.

EXAMPLE of do-while

$a=1
do{
echo $a;
}while($a=3);
Output
1