for
loopfor
statement compared to the while statementfor
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
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
for
loop to display even numbers from 2 to 10echo("<p>"); for ($number = 2; $number <= 10; $number += 2) { echo("$number<br />"); } echo("</p>\n");
$number = 2$number = 4$number = 6$number = 8$number = 10
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
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");
for
statement is useful when you need to increment or decrement a counter that determines how many times the for
loop is executed.for
statement, you code an expression that assigns a starting value to a counter variable, a conditional expression that determines when the loop ends, and an increment expression that indicates how the counter should be incremented or decremented each time through the loop.for
statement syntax, you end the statement with the endfor
keyword.