PHP Program to Convert Kilometers into Miles

In this example, we will write a PHP program to convert Kilometers into Miles. The formula is very simple, 1 kilometer is equal to 0.62137119 miles, which is the conversion factor from kilometers to miles.

So we just have to multiply the kilometer value with 0.62137119, eg: 5 kms x 0.62137119 = 3.1068 miles.

Here is a simple PHP Snippet:

<?php

$kms = 5;
    
//1 km is equal to 0.62137119 so the conversion factor is
$cf = 0.62137119;

$result = $kms * $cf;

?>

Let’s write the same with a beautiful HTML form to get the Kilometer input from the user and convert into miles and display the result on the browser.

<?php 

if ( isset($_POST['convert']) ) {
    
    $kms = $_POST['kms'];
    
    //1 km is equal to 0.62137119 so the conversion factor is
    $cf = 0.62137119;

    $result = $kms * $cf;
}
?>
<!doctype html>
<html lang="en">
  <head>
    <title>PHP program to Convert Kilometers into Miles</title>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  </head>
  <body>
  <div class="container">
      <div class="row">
          <div class="col">
              <form method="post" action="">
              <br><h2>PHP program to Convert Kilometers into Miles</h2><br>
              <div class="form-group">
                  <label for="kms"><h4>Enter Kms</h4></label>
                  <input type="text" min="0" value="<?=(isset($kms)) ? $kms : '10';?>" name="kms" class="form-control" pattern="[0-9]*" title="Please enter only numbers">
                  <small id="helpId" class="text-muted">Enter the Kms in numbers and click the button to Convert it</small>
              </div>
              <div class="form-group">
                  <h5>Result:<span id="res"> <?=(isset($result)) ? $result : '';?></span></h5>
              </div> 
              <div class="form-group">
                  <button type="submit" name="convert" class="btn btn-primary">Convert to Miles</button>
              </div>
              </form>
          </div>
      </div>
    </div>
  </body>
</html>

It’s a simple program, so go through the above lines of code to understand the functionality.

You can see the live of the above PHP program here,

demo

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top