Forum

Number Of Page View:100,000+/Months
LOGIN |New User

Reply

How to use while,do..while,for and foreach loop in PHP?
Below I have given u how to use while, do.while, for and foreach loop in PHP. 
1.while:Uses, we want to execute a line of code many times till specific condition is true.
Syntax:
while (condition)
code will be executed;//When condition is true
Example:
<html>
<body>
<?php 
$m=3;
while($3<=6)
  {
  echo "Number is " . $m . "<br />";
  $m++;
  }
?>
</body>
</html>
2.do..while:Uses, we want to execute a block of code at least one time. After that it checks the condition, till its correct the block of code will executed.Otherwise stopped the execution.
Syntax:
do
{
code will be executed;
}
while (condition);//loop execute atleast one time whenever condition is true or false
Example:
<html>
<body>
<?php 
$m=2;
do
  {
  $m++;
  echo "Number is " . $m . "<br />";
  }
while ($m<7);
?>
</body>
</html>
3.for:Uses, When we want execute a block of code for some specific times.
Syntax:
for (initialize; condition; increment/decrement)
{
  code will be executed;
}
Example:
<html>
<body>
<?php
for ($m=2; $m<=4; $m++)
{
  echo "R4R Welcomes You!<br />";
}
?>
</body>
</html>
4.foreach:Uses, When When we want execute a block of code for each element in an array.
Syntax:
foreach (array as value)
{
    code will be executed;
}
Example:
<html>
<body>
<?php
$arr=array("one", "two", "three");
foreach ($arr as $value)
{
  echo "Value: " . $value . "<br />";
}
?>
</body>
</html>