Get latest news and Web Designing tutoria

Saturday, 30 May 2015

PHP While Loops

Instead of using a for loop, you have the option to use a while loop. The structure of a while loop is more simple than a for loop, because you’re only evaluating the one condition. The loop goes round and round while the condition is true. When the condition is false, the programme breaks out of the while loop. Here’s the syntax for a while loop:
while (condition) {
statement

}
And here’s some code to try. All it does is increment a variable called counter:
$counter = 1;
while ($counter < 11) {
print (" counter = " . $counter . "<BR>");
$counter++;
}
The condition to test for is $counter < 11. Each time round the while loop, that condition is checked. If counter is less than eleven then the condition is true. When $counter is greater than eleven then the condition is false. A while loop will stop going round and round when a condition is false.
If you use a while loop, be careful that you don’t create an infinite loop. You’d create one of these if you didn’t provide a way for you condition to be evaluated as true. We can create an infinite loop with the while loop above. All we have to do is comment out the line where the $counter variable is incremented. Like this:
$counter = 1;
while ($counter < 11) {
print (" counter = " . $counter . "<BR>");
//$counter++;
}
Notice the two forward slashes before $counter++. This line will now be ignored. Because the loop is going round and round while counter is less than 11, the loop will never end – $counter will always be 1.
Here’s a while loop that prints out the 2 times table. Try it out in a script.
$start = 1;
$times = 2;
$answer = 0;
while ($start < 11) {
$answer = $start * $times;
print ($start . " times " . $times . " = " . $answer . "<BR>");
$start++;
}
The while loop calculates the 2 times tables, up to a ten times 2. Can you see what’s going on? Make sure you understand the code. If not, it’s a good idea to go back and read this section again. You won’t be considered a failure. Honest!
In the next part, we'll have a brief look at Do ... While loops

0 comments:

Post a Comment