PHP/Statement/While loop — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Версия 13:37, 26 мая 2010
Содержание
- 1 Approximating a square root
- 2 A sample while loop that counts to 10
- 3 A while Statement
- 4 Convert the while statement into a for statement?
- 5 Create a while statement that prints every odd number between 1 and 49
- 6 Fahrenheit and Celsius table by while loop
- 7 Infinite Loops
- 8 Printing a <select> menu with while()
- 9 The do...while Statement
- 10 while and loop counter
Approximating a square root
<source lang="html4strict">
<HTML> <HEAD> <TITLE>Approximating a square root</TITLE> </HEAD> <BODY> <?php $target = 81; $guess = 1.0; $precision = 0.0000001; $guess_squared = $guess * $guess; while (($guess_squared - $target > $precision) or ($guess_squared - $target < - $precision)) {
print("Current guess: $guess is the square root of $target
"); $guess = ($guess + ($target / $guess)) / 2; $guess_squared = $guess * $guess;
}
print("$guess squared = $guess_squared
");
?>
</BODY>
</HTML>
</source>
A sample while loop that counts to 10
<source lang="html4strict">
<?php $num = 1; while ($num <= 10){
print "Number is $num
"; $num++;
} print "Done."; ?>
</source>
A while Statement
<source lang="html4strict">
<html>
<head>
<title>A while Statement</title>
</head>
<body>
<?php
$counter = 1;
while ( $counter <= 12 ) {
print "$counter times 2 is ".($counter*2)."
"; $counter++;
} ?> </body> </html>
</source>
Convert the while statement into a for statement?
<source lang="html4strict">
<? $num = 1; while ( $num <= 49 ) {
print "$num
"; $num += 2;
} for ( $num = 1; $num <= 49; $num += 2 ) {
print "$num
\n";
} ?>
</source>
Create a while statement that prints every odd number between 1 and 49
<source lang="html4strict">
<? $num = 1; while ( $num <= 49 ) {
print "$num
"; $num += 2;
} ?>
</source>
Fahrenheit and Celsius table by while loop
<source lang="html4strict">
$fahr = -50; $stop_fahr = 50;
print "Fahrenheit | Celsius |
---|---|
$fahr | $celsius |
</source>
Infinite Loops
<source lang="html4strict">
<?php
while(1) { print "In loop!\n"; } ?>
As "1" also evaluates to true, that loop will continue on forever.
<?php for (;;) { print "In loop!\n"; } ?> </source>
<source lang="html4strict">
<? $i = 1; print "<select name="people">"; while ($i <= 10) {
print "<option>$i</option>\n"; $i++;
} print "</select>"; ?>
</source>
The do...while Statement
<source lang="html4strict">
<html> <head> <title>The do...while Statement</title> </head> <body>
<?php
$num = 1; do { print "Execution number: $num
\n"; $num++; } while ( $num > 200 && $num < 400 );
?>
</body> </html>
</source>
while and loop counter
<source lang="html4strict">
<?php
$count = 1; while ($count < 5) { echo "$count squared = ".pow($count,2). "
"; $count++; }
?>
</source>