Larry Ullman's Book Forums

# Ch3, My Solution To Pursue Exercises, In One Script

## Recommended Posts

Hi All,

Here is my solution to Pursue exercises in CH3. I combined 4 questions into one script. If you could take a look at my code and correct if I am wrong, I would be reaaaaly appreciated!

Here are the questions on the book:

# 1. Change calculator.php so that it uses a constant in lieu of the hard-coded average speed of 65.
# 2. Better yet, modify calculator.php so that the user can enter the average speed or select it from a list
# of options.
# 3. Update the output of calculator.php so that it displays the number of days and hours the trip will take, when the number of hours is greater than 24.
# 4. As a more advanced trick, rewrite calculator.php so that the create_radio( ) function call is only in
#  the script once, but still creates three radio buttons. Hint: Use a loop.

Here is my solution script: ( I highlighted the code for the solution )

<?php
# Script 3.10 - calculator.php #5 - Pursue
# 1. Change calculator.php so that it uses a constant in lieu of the hard-coded average speed of 65.
# 2. Better yet, modify calculator.php so that the user can enter the average speed or select it from a list
# of options.
# 3. Update the output of calculator.php so that it displays the number of days and hours the trip will take,
# when the number of hours is greater than 24.
# 4. As a more advanced trick, rewrite calculator.php so that the create_radio( ) function call is only in
#  the script once, but still creates three radio buttons. Hint: Use a loop.
#
#
// This function creates a radio button.
// The function takes two arguments: the value and the name.
// The function also makes the button "sticky".
function create_radio(\$value, \$name = 'gallon_price') {

// Start the element:
echo '<input type="radio" name="' . \$name . '" value="' . \$value . '"';

// Check for stickiness:
if (isset(\$_POST[\$name]) && (\$_POST[\$name] == \$value)) {
echo ' checked="checked"';
}

// Complete the element:
echo " /> \$value ";
}

// This function calculates the cost of the trip.
// The function takes three arguments: the distance, the fuel efficiency, and the price per gallon.
// The function returns the total cost.
function calculate_trip_cost(\$miles, \$mpg, \$ppg) {

// Get the number of gallons:
\$gallons = \$miles / \$mpg;

// Get the cost of those gallons:
\$dollars = \$gallons * \$ppg;

// Return the formatted cost:
return number_format(\$dollars, 2);
}

// End of calculate_trip_cost() function.

\$page_title = 'Trip Cost Calculator';

// PURSUE 1 - Define the constant for average speed:
define ('AVERAGE_SPEED', 65);

// Check for form submission:
if (\$_SERVER['REQUEST_METHOD'] == 'POST') {

// Minimal form validation:
if (isset(\$_POST['distance'], \$_POST['gallon_price'], \$_POST['efficiency'], \$_POST['average_speed']) &&
is_numeric(\$_POST['distance']) && is_numeric(\$_POST['gallon_price']) && is_numeric(\$_POST['efficiency']) && is_numeric(\$_POST['average_speed'])) {

// Calculate the results:
\$cost = calculate_trip_cost(\$_POST['distance'], \$_POST['efficiency'], \$_POST['gallon_price']);
//\$hours = \$_POST['distance'] / AVERAGE_SPEED;
\$hours = \$_POST['distance'] / \$_POST['average_speed'];

// PURSUE 3 - Calculate days and modulus
\$days = \$hours / 24;
\$days_modulus = \$days % 24;

// PURSUE 3 - Print the results, using Days and Hours
if ( \$hours <= 24) {
echo '<h1>Total Estimated Cost</h1>
<p>The total cost of driving ' . \$_POST['distance'] . ' miles, averaging ' . \$_POST['efficiency'] . ' miles per gallon,
and paying an average of \$' . \$_POST['gallon_price'] . ' per gallon, is \$' . \$cost . '. If you drive at
an average of ' . \$_POST['average_speed'] . ' miles per hour, the trip will take
approximately ' . number_format(\$hours, 2) . ' hours.</p>';
} else {
echo '<h1>Total Estimated Cost</h1>
<p>The total cost of driving ' . \$_POST['distance'] . ' miles, averaging ' . \$_POST['efficiency'] . ' miles per gallon,
and paying an average of \$' . \$_POST['gallon_price'] . ' per gallon, is \$' . \$cost . '. If you drive at
an average of ' . \$_POST['average_speed'] . ' miles per hour, the trip will take
approximately ' . number_format(\$days, 2) . ' days and ' . \$days_modulus . ' hours.</p>';

}
} else { // Invalid submitted values.
echo '<h1>Error!</h1>
<p class="error">Please enter a valid distance, price per gallon, fuel efficiency and average speed.</p>';
}
} // End of main submission IF.
// Leave the PHP section and create the HTML form:
?>

<h1>Trip Cost Calculator</h1>
<form action="" method="post">
<p>Distance (in miles): <input type="text" name="distance" value="<?php if (isset(\$_POST['distance'])) echo \$_POST['distance']; ?>" /></p>
<p>Ave. Price Per Gallon: <span class="input">
<?php
// PURSUE 4  the create_radio( ) function call is only in the script once
// Step 1: create an array to hole the three radio button values:
\$radio_values = array('3.00', '3.50', '4.00', '5.00');

// Step 2: use a foreach loop to loop through the array:
}
?>
</span></p>
<p>Fuel Efficiency: <select name="efficiency">
<option value="10"<?php if (isset(\$_POST['efficiency']) && (\$_POST['efficiency'] == '10')) echo ' selected="selected"'; ?>>Terrible</option>
<option value="20"<?php if (isset(\$_POST['efficiency']) && (\$_POST['efficiency'] == '20')) echo ' selected="selected"'; ?>>Decent</option>
<option value="30"<?php if (isset(\$_POST['efficiency']) && (\$_POST['efficiency'] == '30')) echo ' selected="selected"'; ?>>Very Good</option>
<option value="50"<?php if (isset(\$_POST['efficiency']) && (\$_POST['efficiency'] == '50')) echo ' selected="selected"'; ?>>Outstanding</option>
</select></p>
<!-- // PURSUE 2 - Let user enter average speed: (Select from a list of options is not implemented here) -->
<p>Average Speed: <input type="text" name="average_speed" value="<?php if (isset(\$_POST['average_speed'])) echo \$_POST['average_speed']; ?>"></p>
<p><input type="submit" name="submit" value="Calculate!" /></p>
</form>

<?php include ('includes/footer.html'); ?>

• 1
##### Share on other sites

Thanks for sharing. This looks pretty good. My only recommendation is that I would move the division of \$hours/24 to within the conditional if hours is > 24 (i.e., in that else clause).

##### Share on other sites

Thanks Larry, I got it; that way these two variables \$days and \$days_modulus:

\$days = \$hours / 24;
\$days_modulus = \$days % 24;

are not needed, which makes the code concise.

I moved them into the 'else' conditional:

} else {  // \$hours > 24
echo '<h1>Total Estimated Cost</h1>
<p>The total cost of driving ' . \$_POST['distance'] . ' miles, averaging ' . \$_POST['efficiency'] . ' miles per gallon,
and paying an average of \$' . \$_POST['gallon_price'] . ' per gallon, is \$' . \$cost . '. If you drive at
an average of ' . \$_POST['average_speed'] . ' miles per hour, the trip will take
approximately ' . number_format( \$hours / 24, 2) . ' days and ' . (\$hours / 24) % 24 . ' hours.</p>';

-------------

Here is the updated full script:

<?php
# Script 3.10 - calculator.php #5 - Pursue
# 1. Change calculator.php so that it uses a constant in lieu of the hard-coded average speed of 65.
# 2. Better yet, modify calculator.php so that the user can enter the average speed or select it from a list
# of options.
# 3. Update the output of calculator.php so that it displays the number of days and hours the trip will take,
# when the number of hours is greater than 24.
# 4. As a more advanced trick, rewrite calculator.php so that the create_radio( ) function call is only in
#  the script once, but still creates three radio buttons. Hint: Use a loop.
#
#
// This function creates a radio button.
// The function takes two arguments: the value and the name.
// The function also makes the button "sticky".
function create_radio(\$value, \$name = 'gallon_price') {

// Start the element:
echo '<input type="radio" name="' . \$name . '" value="' . \$value . '"';

// Check for stickiness:
if (isset(\$_POST[\$name]) && (\$_POST[\$name] == \$value)) {
echo ' checked="checked"';
}

// Complete the element:
echo " /> \$value ";
}

// This function calculates the cost of the trip.
// The function takes three arguments: the distance, the fuel efficiency, and the price per gallon.
// The function returns the total cost.
function calculate_trip_cost(\$miles, \$mpg, \$ppg) {

// Get the number of gallons:
\$gallons = \$miles / \$mpg;

// Get the cost of those gallons:
\$dollars = \$gallons * \$ppg;

// Return the formatted cost:
return number_format(\$dollars, 2);
}

// End of calculate_trip_cost() function.

\$page_title = 'Trip Cost Calculator';

// PURSUE 1 - Define the constant for average speed:
define ('AVERAGE_SPEED', 65);

// Check for form submission:
if (\$_SERVER['REQUEST_METHOD'] == 'POST') {

// Minimal form validation:
if (isset(\$_POST['distance'], \$_POST['gallon_price'], \$_POST['efficiency'], \$_POST['average_speed']) &&
is_numeric(\$_POST['distance']) && is_numeric(\$_POST['gallon_price']) && is_numeric(\$_POST['efficiency']) && is_numeric(\$_POST['average_speed'])) {

// Calculate the results:
\$cost = calculate_trip_cost(\$_POST['distance'], \$_POST['efficiency'], \$_POST['gallon_price']);
//\$hours = \$_POST['distance'] / AVERAGE_SPEED;
\$hours = \$_POST['distance'] / \$_POST['average_speed'];

// PURSUE 3 - Output displays the number of days and hours the trip will take
if ( \$hours <= 24) {
echo '<h1>Total Estimated Cost</h1>
<p>The total cost of driving ' . \$_POST['distance'] . ' miles, averaging ' . \$_POST['efficiency'] . ' miles per gallon,
and paying an average of \$' . \$_POST['gallon_price'] . ' per gallon, is \$' . \$cost . '. If you drive at
an average of ' . \$_POST['average_speed'] . ' miles per hour, the trip will take
approximately ' . number_format(\$hours, 2) . ' hours.</p>';
} else {  // \$hours > 24
echo '<h1>Total Estimated Cost</h1>
<p>The total cost of driving ' . \$_POST['distance'] . ' miles, averaging ' . \$_POST['efficiency'] . ' miles per gallon,
and paying an average of \$' . \$_POST['gallon_price'] . ' per gallon, is \$' . \$cost . '. If you drive at
an average of ' . \$_POST['average_speed'] . ' miles per hour, the trip will take
approximately ' . number_format( \$hours / 24, 2) . ' days and ' . (\$hours / 24) % 24 . ' hours.</p>';

}
} else { // Invalid submitted values.
echo '<h1>Error!</h1>
<p class="error">Please enter a valid distance, price per gallon, fuel efficiency and average speed.</p>';
}
} // End of main submission IF.
// Leave the PHP section and create the HTML form:
?>

<h1>Trip Cost Calculator</h1>
<form action="" method="post">
<p>Distance (in miles): <input type="text" name="distance" value="<?php if (isset(\$_POST['distance'])) echo \$_POST['distance']; ?>" /></p>
<p>Ave. Price Per Gallon: <span class="input">
<?php
// PURSUE 4 - the create_radio( ) function call is only in the script once
// Step 1: create an array to hold the three/four/... radio button values:

\$radio_values = array('3.00', '3.50', '4.00', '5.00');

// Step 2: use a foreach loop to loop through the array:
}
?>
</span></p>
<p>Fuel Efficiency: <select name="efficiency">
<option value="10"<?php if (isset(\$_POST['efficiency']) && (\$_POST['efficiency'] == '10')) echo ' selected="selected"'; ?>>Terrible</option>
<option value="20"<?php if (isset(\$_POST['efficiency']) && (\$_POST['efficiency'] == '20')) echo ' selected="selected"'; ?>>Decent</option>
<option value="30"<?php if (isset(\$_POST['efficiency']) && (\$_POST['efficiency'] == '30')) echo ' selected="selected"'; ?>>Very Good</option>
<option value="50"<?php if (isset(\$_POST['efficiency']) && (\$_POST['efficiency'] == '50')) echo ' selected="selected"'; ?>>Outstanding</option>
</select></p>
<!-- // PURSUE 2 - Let user enter average speed: (Select from a list of options is not implemented here) -->
<p>Average Speed: <input type="text" name="average_speed" value="<?php if (isset(\$_POST['average_speed'])) echo \$_POST['average_speed']; ?>"></p>
<p><input type="submit" name="submit" value="Calculate!" /></p>
</form>

<?php include ('includes/footer.html'); ?>

• 1
##### Share on other sites

Excellent. Thanks again for sharing!

##### Share on other sites

• 7 years later...

Hello!

Please explain why to use the constant of an average speed and then let user enter any value of it into the form. Where this value of 65 goes?

##### Share on other sites

I'm not sure I follow exactly what you're asking but I'll try to answer as best as I can...

First, a constant would be better than using a hardcoded number--65--that has no context and can easily be lost within the code. The constant allows you to "label" the value and makes it easier and more obvious to change down the line.

Second, the next prompt suggests taking the average speed as user input instead of using the hardcoded number or a constant. So you'd just repeat what the calculator does with distance but for the average speed.

• 1
##### Share on other sites

Thank you, Larry. Now it's clear.

I have another solution for Pursue 3, I feel like Christopher's solution is more straightforward and clean but I use the function which allows having less writing (without duplication "The total cost of driving"...). Can you please say a few wise words about my code? ```// Check for form submission:
if (\$_SERVER['REQUEST_METHOD'] == 'POST') {

// Minimal form validation:
if (isset (\$_POST['distance'], \$_POST['gallon_price'], \$_POST['efficiency'], \$_POST['average_speed'])
&& is_numeric(\$_POST['distance']) && is_numeric(\$_POST['gallon_price']) && is_numeric(\$_POST['efficiency']) ) {

// Calculate the results
\$cost = calculate_trip_cost(\$_POST['distance'], \$_POST['efficiency'], \$_POST['gallon_price']);
function travelTime() {
\$hours = \$_POST['distance']/\$_POST['average_speed'];
if (\$hours > 24) {
\$days = \$hours/24;
\$hours2 = \$hours%24; # вывожу целочисленный остаток.
echo number_format(\$days, 0) . ' days and ' . \$hours2 . ' hours';
} else {
echo number_format(\$hours, 2) . ' hours'; }
}

// Print the results:
<h1>Total Estimated Cost</h1></div>
<p>The total cost of driving ' . \$_POST['distance'] . ' miles, averaging ' . \$_POST['efficiency'] . 'miles per gallon, and paying
an average of \$' . \$_POST['gallon_price'] . ' per_gallon, is \$' . \$cost . '. If you drive
at an average of ' . \$_POST['average_speed'] . ' miles per hour, the trip will take approximately ';
echo travelTime();
echo '</p>';
} else {
// invalid submitted values.
<h1>Error!</h1></div><p class="text-danger">Please enter a valid distance, price per gallon, and fuel efficiency.</p>';
}
} // End of main submission IF.```

##### Share on other sites

Two primary issues, one minor:

- (Minor) You call the function with echo but the function itself prints, so this is redundant.
- You really should use global variables in a function, for the most part. Functions should be passed the data they need.

• 1
##### Share on other sites

• 2 weeks later...

Thank you very much! ## Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible. ×   Pasted as rich text.   Paste as plain text instead

Only 75 emoji are allowed.

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.