Using Loops in PHP

Loops are an vital part of a programming language. Typically the need to use loops in a program occur when you want to execute a piece of code repeatedly until a desired condition is achieved. There are many control structures that can be use to implement looping in a program.

The While loop

The while loop is one is the simplest looping control structure in PHP. When you specify a condition and a code block along with the while loop, the code block is repeatedly execute until the condition becomes false.

<?php
$a = 1;
while ($a <= 10){
  echo $a ."<br/>";
}
?>

The for loop

The for loop is similar to the while loop and can achieve the same result. It is use to evaluate a set of conditional expression at the beginning of each loop. The for loop is one of the most complex loop in PHP.

<?php
for ($a=1; $a <=10 ; $a++){
  echo $a ."<br/>";
}
?>


Breaking a loop

Sometimes, you might want to break a loop before it complete execution .The break statement can do this.
 
<?php
for ($a=1; $a <=10 ; $a++){
echo $a ."<br/>";
  if($a==5){
    break;
  }
}
?>

The continue statement

The continue statement is the reverse  the break statement, doesn't breaks a loop. When you break a loop the loop with the break statement, you can't check for the same condition again. The continue statement just skip the specific iteration and doesn't cause the loop to end.

<?php
for ($i = 0; $i < 5; ++$i) {
if ($i == 2)
continue
  echo $i;
}
?>

The output will be: 2.

Nesting loops

Nesting loops are a way to use a loop statement within another statement. for example, if you have a loop x, and have another loop y in the loop y in the loop x, the loop y will be executed x*y.

<?php
for ($a =10; $a <= 15; $a++){
    echo "First Loop <br/>";
       for ($b = 5; $b < 10; $b++){
           echo "Second Loop <br/>";
       }
}
?>

Top