Loops
$i = 1;
while ($i < 100) {
... stuff to be repeated
$i++;
}
There are three things to note here:
1. Set and use a variable to control the loop. $i is commonly used as the loop index
2. Increment the index within the loop. $i++ adds 1 to the value of $i. This means that $i starts at 1 before the loop starts, then goes to 2,3,4 etc. when $i++ is reached.
3. Finish the loop by specifying a condition. Here the loop would end when $i hits 100. Note that this means that the while loop will continue as long as the condition inside the brackets is true.
The second kind of loop is a 'for' loop. This looks like:
for ($i = 1; $i <= 100; $i++) {
... stuff to be repeated
{
Note:
1. This has the same elements as the while loop, but they are all included in the one statement - an initial value for the index, a condition to terminate the loop and the increment of the index.
2. This makes it much easier to loop through for a given number of times.
The main difference is that a 'while' loop is best used to repeat things when it is not know beforehand how many times the loop is needed, The 'for' loop is best used to repeat a set number of times.
Examples:
// Repeat until random number is different to one previously picked
$previous = 4;
$gotnew = false;
while (!$gotnew) {
$number = mt_rand(1,10);
if ($number <> $previous) {
$gotnew = true;
}
}
// Read string one chracter at a time
$string = "Welcome";
for ($i=1; $i<= strlen($string); $i++) {
$new = substr($string, 0, $i);
echo $new;
}
// Program will output W, then We, then Wel, then Welc, etc. upto Welcome
Next article: Arrays