PHP while loop
In this chapter you will learn:
- What is PHP while loop
- Syntax for while loop
- Example - while loop with integer counter
- Example - Infinite Loops
- Example - infinite while loop with break statement
Description
PHP while loops executes a block of code for a given condition.
Syntax
The while loop has the following syntax.
while(condition is true){
do the loop statement
}
Example
For example, this code will loop from 1 to 10, printing out values as it goes:
<?php/* j a v a 2 s . c o m*/
$i = 1;
while($i <= 10) {
print "Number $i\n";
$i = $i + 1;
}
?>
The code above generates the following result.
Example 2
Here are the two most common types of infinite loops:
<?php// ja v a 2 s .co m
while(1) {
print "In loop!\n";
}
?>
Example 3
Infinite while loop with break statement
<?php/*from j ava 2 s. c om*/
$count = 0;
while ( true ) {
$count++;
echo "I ' ve counted to: $count < br / > ";
if ( $count == 10 ) break;
}
?>
The code above generates the following result.
Next chapter...
What you will learn in the next chapter: