[Solved] Script to convert Celsius to Fahrenheit and Fahrenheit to Celsius (Code)

  

3
Topic starter
  • Write a PHP script to convert from Celsius to Fahrenheit
  • Print the result in format "132.8 °F = 56 °C" (use ° for °)
  • Define the degree conversion functions:
function celsiusToFahrenheit(float $celsius) : float
{
    return $celsius * 1.8 + 32;
}
 
function fahrenheitToCelsius(float $fahrenheit) : float
{
    return ($fahrenheit - 32) / 1.8;
}
1 Answer
2

Here is the solution:

<!DOCTYPE html>
<html>
<head>
    <title>Convert</title>
</head>
 
<body>
 
<?php
 
function celToFah(float $degrees)
{
    return $degrees * 1.8 + 32;
}
 
function fahToCel(float $degrees)
{
    return ($degrees - 32) / 1.8;
}
 
if (isset($_GET['cel'])) {
    $cel = floatval($_GET['cel']);
    $fah = celToFah($cel);
    $fahMsg = "$cel &deg;C = $fah &deg;F";
}
 
if (isset($_GET['fah'])) {
    $fah = floatval($_GET['fah']);
    $cel = fahToCel($fah);
    $celMsg = "$fah &deg;F = $cel &deg;C";
}
 
?>
 
 
<form>
    Celsius: <input type="number" name="cel">
    <input type="submit" value="Convert Celsius to Fahrenheit">
    <?php
    if (isset($fahMsg)) {
        echo $fahMsg;
    }
    ?>
</form>
<br>
<form>
    Fahrenheit: <input type="number" name="fah">
    <input type="submit" value="Convert Fahrenheit to Celsius">
    <?php
    if (isset($celMsg)) {
        echo $celMsg;
    }
    ?>
</form>
 
</body>
</html>
Share: