PHP/Statement/While loop
Содержание
- 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
<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<BR>");
$guess = ($guess + ($target / $guess)) / 2;
$guess_squared = $guess * $guess;
}
print("$guess squared = $guess_squared<BR>");
?>
</BODY>
</HTML>
A sample while loop that counts to 10
<?php
$num = 1;
while ($num <= 10){
print "Number is $num<br />";
$num++;
}
print "Done.";
?>
A while Statement
<html>
<head>
<title>A while Statement</title>
</head>
<body>
<?php
$counter = 1;
while ( $counter <= 12 ) {
print "$counter times 2 is ".($counter*2)."<br>";
$counter++;
}
?>
</body>
</html>
Convert the while statement into a for statement?
<?
$num = 1;
while ( $num <= 49 ) {
print "$num<br />";
$num += 2;
}
for ( $num = 1; $num <= 49; $num += 2 ) {
print "$num<br />\n";
}
?>
Create a while statement that prints every odd number between 1 and 49
<?
$num = 1;
while ( $num <= 49 ) {
print "$num<br />";
$num += 2;
}
?>
Fahrenheit and Celsius table by while loop
$fahr = -50;
$stop_fahr = 50;
print "<table>";
print "<tr><th>Fahrenheit</th><th>Celsius</th></tr>";
while ($fahr <= $stop_fahr) {
$celsius = ($fahr - 32) * 5 / 9;
print "<tr><td>$fahr</td><td>$celsius</td></tr>";
$fahr += 5;
}
print "</table>";
Infinite Loops
<?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";
}
?>
<?
$i = 1;
print "<select name="people">";
while ($i <= 10) {
print "<option>$i</option>\n";
$i++;
}
print "</select>";
?>
The do...while Statement
<html>
<head>
<title>The do...while Statement</title>
</head>
<body>
<div>
<?php
$num = 1;
do {
print "Execution number: $num<br />\n";
$num++;
} while ( $num > 200 && $num < 400 );
?>
</div>
</body>
</html>
while and loop counter
<?php
$count = 1;
while ($count < 5) {
echo "$count squared = ".pow($count,2). "<br />";
$count++;
}
?>