Practical Web Programming

Thursday, January 29, 2009

Types of Loops in PHP

A programming loop is a sequence of statements which is specified once but can also be performed several times in succession. Looping construct is one of the most powerful feature of all programming language. Using loops, you can duplicate task to any number of repetitions.

If PHP, this are four types of looping construct, the while, do...while, for and foreach loop. The following example demonstrates how to use each loop.

Using the while loop.

<?php

$x=1;
while($x<=10)
{
echo "The number is " . $x . "<br />";
$x++;
}

?>


while loop output:

The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10


Using the do...while loop.

<?php

$x=1;
do
{
echo "The number is " . $x . "<br />";
$x++;
}
while ($x<10);

?>


do...while loop output:

The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9


Using the for loop.

<?php

for ($x=1; $x<=10; $x++)
{
echo "The number is " . $x . "<br />";
}

?>


for loop output:

The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10


Using the foreach loop.

<?php

$arr=array("one", "two", "three", "four", "five");
foreach ($arr as $value)
{
echo "Value: " . $value . "<br />";
}

?>


foreach loop output:

Value: one
Value: two
Value: three
Value: four
Value: five

0 comments:

Recent Post