HTML, XHTML and CSS All-In-One for Dummies - Andy Harris [220]
The following code shows the basic HTML form:
Distance Calculator, PHP Style
There’s nothing unfamiliar about this form:
1. Set the form’s action to distance.php.
That’s the program that will actually calculate the distance. Use the post method, as usual.
2. Create a select object to determine where the user is leaving.
This form element will be called from because it represents the city the user is coming from. Note that the value is an integer that will relate to the various city numbers (0 for Indianapolis, and so on).
3. Create a second select object for the destination.
The second selection is much like the first, but it has the name to.
4. Use CSS for beautification.
A little CSS can go a long way to make this page look nicer.
Looking up the distance
When the user submits the form, she is rewarded with the display shown in Figure 4-7.
Figure 4-7: This clever program calculates the distance.
Of course, you could calculate the distance between cities with if statements, switches, and the like, but this kind of problem is really a lookup table. That means that the best way to solve it without a computer is to build a table. To use the table, you would use the row to indicate the source and the column to designate the destination, and then see where they cross for a result. It’s very easy to get the computer to do exactly the same thing by using a two-dimension array, as shown in the following code:
$cityName = array(”Indianapolis”, ”New York”, ”Tokyo”, ”London”);
//get variables from form
$from = $_REQUEST[”from”];
$to = $_REQUEST[”to”];
$distance = array(
array(0, 648, 6476, 4000),
array(648, 0, 6760, 3470),
array(6476, 6760, 0, 5956),
array(4000, 3470, 5956, 0));
$result = $distance[$from][$to];
print ”
Distance from $cityName[$from] to $cityName[$to] is $result miles
\n”;?>
The two-dimension array simplifies things greatly. Take a look at how the program calculates the result:
1. Create a standard array to handle city names.
The cities all have numbers, so I use an array to help attach the names to the numbers. It’s important that this array is in the correct order, so city 0 is Indianapolis throughout.
2. Retrieve to and from data from the form.
These values were sent by the previous form, so get the data and place them in variables.
3. Build a 2D array to hold the distance data.
The distance is stored