HomePHP Page 3 - PHP 101 (part 3) - Chocolate Fudge And Time Machines
Revisiting The Past - PHP
After teaching you the fundamentals of form processing, PHP 101 returns with an explanation of WHILE, FOR and FOREACH loops, those PHP constructs that can save you hours of unnecessary HTML coding. Also included: array variables, the auto-increment operator, and some yummy desserts.
So that's the "while" loop - it executes a set of statements until a specified condition is satisfied. But what happens if the condition is satisfied on the first iteration itself? In the illustration above, for example, if you were to enter the year 2000, the "while" loop would not execute even once. Try it yourself and you'll see what we mean.
So, if you're in a situation where you need to execute a set of statements *at least* once, PHP offers you the "do-while" loop. Here's what it looks like:
do
{
do this!
} while (condition)
Let's take a quick example:
<?php
$bingo
= 366;
while ($bingo == 699)
{
echo "Bingo!";
break;
}
?>
In this case, no matter how many times you run this PHP script, you will get
no output at all, since the value of $bingo is not equal to 699. But, if you ran this version of the script
<?php
$bingo = 799;
do
{
echo "Bingo!";
break;
} while ($bingo == 699);
?>
you'd get one line of output.
Thus, the construction of the "do-while" loop is such that the statements within the loop are executed first, and the condition to be tested is checked after. This implies that the statements within the curly braces would be executed at least once.
Let's modify the time machine above to use a "do-while" loop instead:
<?
// if form has not been submitted, display initial page
if (!$submit)
{
?>
<html>
<head>
</head>
<body>
<h2>The
Incredible Amazing Fantabulous Time Machine</h2>
<form action="tmachine.php4"
method="POST">
Which year would you like to visit?
<input type="text" name="year"
size="4" maxlength="4">
<input type="submit" name="submit" value="Go">
</form>
</body>
</html>
<?
}
else
//
else process it and generate a new page
{
?>
<html>
<head>
</head>
<body>
<?
//
current year
$current = 2000;
// check for dates in future and generate appropriate
message
if ($year > $current)
{
echo "<h2>Oops!</h2>";
echo "Sorry,
this
time machine can only travel backwards at the moment.
But leave your phone
number
and we'll call you when the new improved model
goes on sale.";
}
else
{
// or
echo "<b>Going back to $year...</b><br>";
// in this case,
the "do-while"
loop
// ensures that at least one line of output is generated
//
even when you
enter the year 2000
do
{
$current = $current - 1;
echo
"$current ";
} while($year < $current);
echo "<br><b>The past definitely
isn't all
it's cracked up to be!</b>";
}
?>
</body>
</html>
<?
}
?>