SakhaliaNetHome PageSahara TerritoryVorKutaAcceptance of cookiesAcceptance of cookies

PHP Tutorial :: Loops

PHP Example #27

While() loop

Loops are an essential part of programming languages. They allow to execute an action automatically so many times as necessary. The running of loops is always controlled by one or more variables; the way in which these control variables are managed depends on the type of loop. In this example we see how the while() loop works in cooperation with $i, the control variable, to print the elements of a select list; when $i reaches the value 11, the loop will stop.

<?php
$i = 1;
print '<select name="people">';
while ($i <= 10) {
$format_i = sprintf('%02d',$i);
$string = "----------";
$string = substr($string, 0, $i);
print nl2br("<option>$format_i $string</option>\n");
$i++;
}
print '</select>';
?>

PHP Example #28

For() loop

The for() loop works similarly to the while() loop, but it encompass in its declaration the three checking expressions that a loop needs to operate; the first one allows to set an initial value to the control variable, the second one indicates when the loop has to stop and the third one indicates which will be the increment of the control variable on each iteration.

We can say that for() loops are a more developed version of while() loops, since these had the initialization and increment statements placed outside and inside the loop, respectively, while the for() loop reunites the three expressions in the declaration of the loop, improving the readability of the source code.

<?php
print '<select name="people">';
for ($i = 1; $i <= 10; $i++) {
$format_i = sprintf('%02d',$i);
$string = "----------";
$string = substr($string, 0, $i);
print nl2br("<option>$format_i $string</option>\n");
}
print '</select>';
?>

PHP Example #29

For() loop with multiple expressions

For more complex tasks, we can assign to a for() loop multiple expressions for initialization and iteration, separating individual expressions with commas.

<?php
print '<select name="doughnuts">';
for ($min = 1, $max = 10; $min < 50; $min += 10, $max += 10) {
$format_min = sprintf('%02d',$min);
$format_max = sprintf('%02d',$max);
$string = "-----";
$string = substr($string, 0, ($min / 10) + 1);
print nl2br("<option>$format_min - $format_max $string</option>\n");
}
print '</select>';
?>