HomePHP Page 2 - PHP 101 (part 3) - Chocolate Fudge And Time Machines
Back To The Future - 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.
For those of you unfamiliar with the term, a loop is a control structure which enables you to repeat the same set of PHP statements or commands over and over again; the actual number of repetitions may be dependent on a number you specify, or on the fulfillment of a certain condition or set of conditions.
The first - and simplest - loop to learn in PHP is the so-called "while" loop, which looks like this:
or, in English,
while (it's raining)
carry an umbrella!
In this case, so long as the condition specified evaluates as true - remember
what you learned last time? - the PHP statements within the curly braces will continue to execute. As soon as the condition becomes false - the sun comes out, for example - the loop will be broken and the statements following it will be executed.
Here's a quick example which demonstrates the "while" loop:
// if form has not been submitted, display initial page
Incredible Amazing Fantabulous Time Machine</h2>
Which year would you like to visit?
<input type="text" name="year"
<input type="submit" name="submit" value="Go">
else process it and generate a new page
$current = 2000;
// check for dates in future and generate appropriate
if ($year > $current)
time machine can only travel backwards at the moment.
But leave your phone
and we'll call you when the new improved model
goes on sale.";
echo "<b>Going back to $year...</b><br>";
// use a while loop
a series of numbers (years)
// until the desired number (year) is reached
$current = $current - 1;
echo "$current ";
past definitely isn't all it's cracked up to be!</b>";
In this case, we first ask the user for the year he'd like to visit - this year
is stored as the variable $year, and passed to the PHP script. The script first checks the year to ensure that it in the past [hey, we're working on it!] and then uses a "while" loop to count backwards from the current year - 2000, stored in the variable $current - until the values of $current and $year are equal.
Note our usage of the $submit variable to use the same PHP page to generate both the initial form and the subsequent pages - we explained this technique in detail last time.