How to code the for loop

The for statement compared to the while statement

The for statement

      $count = 1;
      echo("<p>");
      for ($count = 1; $count <= 10; $count++) {
        echo("\$count = $count<br />\n");
      }
      echo("</p>\n");
      

$count = 1 $count = 2 $count = 3 $count = 4 $count = 5 $count = 6 $count = 7 $count = 8 $count = 9 $count = 10

The while statement

      $count = 1;
      echo("<p>");
      while ($count <= 10) {
        echo("\$count = $count<br />\n");
        $count++;
      }
      echo("</p>\n");
      

$count = 1 $count = 2 $count = 3 $count = 4 $count = 5 $count = 6 $count = 7 $count = 8 $count = 9 $count = 10

A for loop to display even numbers from 2 to 10

      echo("<p>");
      for ($number = 2; $number <= 10; $number += 2) {
        echo("$number<br />");
      }
      echo("</p>\n");   
      

$number = 2$number = 4$number = 6$number = 8$number = 10

A for loop to display all the factors of a number

      $number = 18;
      echo("<p>");
      for ($i = 1; $i < $number; $i++) {
        if ($number % $i == 0) { 
          echo("$i is a factor of $number . '");
        }
      }
      echo("</p>");
      

1 is a factor of 182 is a factor of 183 is a factor of 186 is a factor of 189 is a factor of 18

A for loop that uses the alternate syntax to display an HTML5 drop-down list (select)

      echo("<label>Interest Rate:</label>\n");
      echo("<select name='rate' id='rate'>\n");
      echo("for ($v = 5; $v <= 12; $v++) : \n");
      echo("  <option value='$v'">$v</option>\n");
      echo("endfor;\n");
      echo("</select>\n");
      

Back