Created
December 28, 2022 06:05
-
-
Save shibbirweb/7310a022cb8ea75dc93bd02a4d7fda25 to your computer and use it in GitHub Desktop.
Backward and forward unit converter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Function to convert a value from one unit to another | |
function convert_unit($value, $from_unit, $to_unit) { | |
// Conversion factors | |
$conversions = [ | |
'meter' => [ | |
'inch' => 39.3700787, | |
'foot' => 3.2808399, | |
'yard' => 1.0936133, | |
'mile' => 0.000621371192 | |
], | |
'inch' => [ | |
'meter' => 0.0254, | |
'foot' => 0.0833333333, | |
'yard' => 0.0277777778, | |
'mile' => 0.0000157828283 | |
], | |
// Add more conversion factors here | |
]; | |
// Check if the from unit and the to unit are the same | |
if ($from_unit == $to_unit) { | |
return $value; | |
} | |
// Check if a conversion factor exists for the from unit and the to unit | |
if (!isset($conversions[$from_unit][$to_unit])) { | |
// If not, try to find the reverse conversion factor | |
if (!isset($conversions[$to_unit][$from_unit])) { | |
// If the reverse conversion factor does not exist, return an error message | |
return "Error: Conversion from $from_unit to $to_unit is not supported."; | |
} | |
// If the reverse conversion factor exists, use it to convert the value | |
$converted_value = $value / $conversions[$to_unit][$from_unit]; | |
} else { | |
// If a conversion factor exists, use it to convert the value | |
$converted_value = $value * $conversions[$from_unit][$to_unit]; | |
} | |
return $converted_value; | |
} | |
// Test the function | |
$value = 10; | |
$from_unit = 'meter'; | |
$to_unit = 'inch'; | |
$converted_value = convert_unit($value, $from_unit, $to_unit); | |
echo "$value $from_unit is equal to $converted_value $to_unit."; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment