PHP Tutorials


PHP Looping
March 2, 2008, 8:58 am
Filed under: PHP

This is used to execute same codes at specified number of times.

There are four PHP looping statements:

  • while – will continue looping through the code as long as the condition is true
  • do…while – loops through the code then if the condition is true then it continues otherwise it will end the loop
  • for – loops through the code while the condition is true
  • foreach – loops through the code for each element in an array

The while statement
This will continue to execute the code as long as the condition is true. Below is the syntax:

while (condition)
code to be executed;

Below is an example:

It will continue to execute the code as long as the variable x is less than 3. Variable x will increase by 1 every time the code is executed.

<html>
<body>
<?php
$x = 0;
while($x<3)
{
echo “Display me 3 times. <br />”;
$x++;
}
?>
</body>
</html>

The do…while statement

Loops through the code then if the condition is true then it continues otherwise it will end the loop.
Below is the syntax:

do
{
code to be executed;
}
while (condition);

Below is an example:

It will continue to execute the code as long as the variable x is less than 3. Variable x will increase by 1 every time the code is executed.

<html>
<body>
<?php
$x=0;
while ($x<3)
{
echo “display me 3 times. <br />”;
$x++;
}
?>
</body>
</html>

The for statement
Loops through the code while the condition is true. Below is the syntax:

for (initialization; condition; increment)
{
code to be executed;
}

Below is an example:
It will display the text “Display me 3 times.” 3 times.

<html>
<body>
<?php
for($x=0;$x<3;$x++)
{
echo “Display me 3 times. <br />”;
}
?>
</body>
</html>

The foreach statement
This is used to loop through arrays. For every loop, the value of the current array is assigned to $value so on the next loop, you’ll be looking at the next element. Below is the syntax:

foreach (array as value)
{
code to be executed;
}

Below is an example:

<html>
<body>
<?php
$myarray = array(“Learn”, “PHP”,”Now”);

for each($myarray as $value)
{
echo $value . “<br />”;
}

?>
</body>
</html>


No Comments Yet so far
Leave a comment



Leave a comment
Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>