PHP Programming

Hands On No. 11 : Working with loops in PHP

Working with loops in PHP

while Loop

                              

Syntax

while (condition is true)
{

code to be executed;

}

Example

<?php

$x = 1;
while($x <= 5)
{
echo "The number is: $x <br>";
$x++;
}

?>

do...while Loop
                              

Syntax

do {

code to be executed;

} while (condition is true);

Example

<?php

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

?>

for Loop
                              

Syntax

for (init counter; test counter; increment counter) {

code to be executed for each iteration;

}

Example 

<?php

for ($x = 0; $x <= 10; $x++) {

echo "The number is: $x <br>";

}

?>

<?php

for($i=0;$i<=5;$i++){

for($j=0;$j<=$i;$j++){

$str = chr($i+97);

echo( $str);

}

echo "<br/>";

}

?>

 

foreach Loop
                              

Syntax

foreach ($array as $value) {

code to be executed;

}

Example 

<?php

$cars = array("Audi", “MG", "Tata", "Ford");
foreach ($cars as $value)
{
echo "$value <br>";
}

?>