PHP lessons

Iteration

How many of these do you want?

bassotto (17K)

You can choose among:

How many of these do you want? (max 10)

This little program above is made by an iterative structure or cycle; this structure allows to repeat an instruction or a group of instructions for a certain number of times.

In PHP there are 3 kind of iterative structures:

The while instruction can fit every kind of problems: it needs to define a condition only, i.e. a variable or a boolean expression (its value can be TRUE or FALSE). This condition controls the end of the cycle.

Look at the syntax of the 3 instructions:

while (condition) {
instruction;
instruction;
... ;
};
do {
instruction;
instruction;
... ;
} while (condition);
for ($i=0; $i<$n; $i++) {
instruction;
instruction;
... ;
};
The cycle (between curly brackets) is repeated while the condition is TRUE.
If at the beginnig the condition is false, the cycle isn't executed. Pay attention: if the condition is always true, we have a neverendig cycle!
The control is at the end, therefore the cycle (between curly brackets) is repeated once at least. After the first time, the cycle is repeated only if the condition is FALSE, otherwise it stops. Pay attention: if the condition is always false, we have a neverendig cycle! The cycle (between curly brackets) is repeated for a fixed number of times.
A variable takes an initial value which is automatically increased every time.

Here it is the code of the program How many of these do you want?:

code of cycle.htmcode of cycle.php
<body>
<form action="cycle.php" method=post>
<p>You can choose among:
<select name="choice">
<option value="SMACK">kisses</option>
<option value="SLAP">slaps</option>
<option value="PAT">encouragements</option>
</select>
</p>
<p>How many of these do you want?
<input type='text' name='n'>
<input type='submit' value="Go"></p>
</form>
</body>
<body>

<?php
$i = 0; //the counter is set to zero
while ($i < $n) {
echo"$choice<br />";
$i++;
}; // end of the cycle
?>

</body>
A HTML page accepts, by a select tag, a variable called choice which assumes values: SMACK, SLAP or PAT depending on the user's choice. Furthermore it accepts a numerical variable n The PHP program works by a while cycle: it repeats the content of the variable $choice until the counter $i is equal to $n

Valid HTML 4.01 Transitional