Skip to content
Advertisement

Question for PHP Time Calculator Based on Distance

I’m working on a project where I have to calculate the hours and minutes a train ride will take based on distance (in miles/hour), stops taken (5 minutes added per stop), and weather (Good weather train speed is 50 mph, in bad weather it is 40 mph). I’m getting correct output when I run it with good weather but when I enter 50 miles, 2 stops, bad weather, I’m getting 1 hour and 20 minutes when I should get 1 hour and 25 minutes. Here is my full form code:

<!DOCTYPE html>

<html lang="en">
<head>
<title>Passenger Train</title>
</head>
<header>
</header>
<body>
<h1>Passenger Train</h1>
<hr>
<p>Enter the distance and number of stops and specify if the weather  is good or bad.</p>
<form method="POST" action="PassengerTrain.php">
<input type="text" name="distance" /> Distance (in miles)<br />
<input type="text" name="stops" /> Number of Stops<br />
<input type="radio" name="weather" id="goodWeather" value="goodWeather">
<label for="goodWeather">Weather is Good</label><br />
<input type="radio" name="weather" id="badWeather" value="badWeather">
<label for="badWeather">Weather is Bad</label><br />
<input type="submit" name="submit" value="Calc. Travel Time" />
</form>
<?php

if(isset($_POST['submit'])) {
    if(is_numeric($_POST['distance']) && is_numeric($_POST['stops'])) {
        if($_POST['weather'] == "badWeather") {
            $speed = 40;
            }
        else {
            $speed = 50;
            }
        $distance = $_POST['distance'];
        $stops = $_POST['stops'];
        $hours = intval($distance / $speed);
        $minutes = $distance % $speed;
        $extraTime = $stops * 5;
        $minutes += $extraTime;
        if ($minutes > 60) {
            $minutes = $minutes - 60;
            $hours = $hours + 1;
            }
        echo "Based on the information given your trip will take " . $hours . " hours and " . 
$minutes . " minutes.";
    }
    else {
        echo "You must enter numeric values for distance and number of stops.";
    }
}

?>
</body>
</html>

Where could I fix this issue or what did I do wrong?

Advertisement

Answer

As pointed out, the problem is that you are not working the minutes out as minutes.

To reduce the main calculation to 1 step, you can add the stops into the time taken by the speed and distance, dividing the total time for the stops (stops * 5) by 60 (to make it into a decimal representing parts of an hour). Then split this into the hours and minutes without need for any further adjustments…

$time = $distance / $speed + ($stops * 5) / 60;
$hours = intval($time);
$minutes = ($time - $hours) * 60;

which with your values, will give…

Based on the information given your trip will take 1 hours and 25 minutes.
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement