How to Create Length Converter Calculator tool using PHP?

Hello Friends Today, through this tutorial, I will tell you How to Create Length Converter Calculator tool using PHP?.

Here’s a PHP script for a simple length converter:

<?php
// Define supported conversion units
$units = array(
"meter" => array(
"symbol" => "m",
"conversion_rates" => array(
"cm" => 100,
"foot" => 3.28084,
"inch" => 39.37008,
),
),
"centimeter" => array(
"symbol" => "cm",
"conversion_rates" => array(
"meter" => 0.01,
"foot" => 0.0328084,
"inch" => 0.3937008,
),
),
"foot" => array(
"symbol" => "ft",
"conversion_rates" => array(
"meter" => 0.3048,
"cm" => 30.48,
"inch" => 12,
),
),
"inch" => array(
"symbol" => "in",
"conversion_rates" => array(
"meter" => 0.0254,
"cm" => 2.54,
"foot" => 0.0833333,
),
),
);
// Check if form is submitted
if (isset($_POST['submit'])) {
// Get form data
$value = (float) $_POST['value'];
$from_unit = $_POST['from_unit'];
$to_unit = $_POST['to_unit'];
// Check if units are valid
if (!array_key_exists($from_unit, $units) || !array_key_exists($to_unit, $units)) {
$error_message = "Invalid unit(s) selected.";
} else {
// Perform conversion
$conversion_rate = $units[$from_unit]['conversion_rates'][$to_unit];
$converted_value = $value * $conversion_rate;
}
}
?>

html Code

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Length Converter</title>
</head>
<body>
<h1>Length Converter</h1>
<?php if (isset($error_message)): ?>
<p style="color: red;"><?php echo $error_message; ?></p>
<?php endif; ?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<label for="value">Enter value:</label>
<input type="number" name="value" id="value" required>
<br>
<label for="from_unit">From:</label>
<select name="from_unit" id="from_unit" required>
<?php foreach ($units as $unit_name => $unit_data): ?>
<option value="<?php echo $unit_name; ?>"><?php echo $unit_data['symbol']; ?></option>
<?php endforeach; ?>
</select>
<br>
<label for="to_unit">To:</label>
<select name="to_unit" id="to_unit" required>
<?php foreach ($units as $unit_name => $unit_data): ?>
<option value="<?php echo $unit_name; ?>"><?php echo $unit_data['symbol']; ?></option>
<?php endforeach; ?>
</select>
<br>
<button type="submit" name="submit">Convert</button>
</form>
<?php if (isset($converted_value)): ?>
<p><b><?php echo $value; ?> <?php echo $units[$from_unit]['symbol']; ?> is equal to <?php echo $converted_value; ?> <?php echo $units[$to_unit]['symbol']; ?>.</b></p>
<?php endif; ?>
</body>
</html>

This script creates a simple HTML form with dropdowns for selecting the units and a field to enter the value. When the form is submitted, it checks for errors and performs the conversion if valid. Finally, it displays the converted value