Programming Fundamentals/Conditions/PHP

conditions.php

edit
<?php

// This program asks the user to select Fahrenheit or Celsius conversion
// and input a given temperature. Then the program converts the given 
// temperature and displays the result.
//
// References:
//     https://www.mathsisfun.com/temperature-conversion.html
//     https://en.wikibooks.org/wiki/PHP_Programming

function get_choice()
{
    printf("Enter F to convert to Fahrenheit or C to convert to Celsius: ");
    $choice = readline();
    return $choice;
}

function process_celsius()
{
    $temperature = get_temperature("Fahrenheit");
    $result = calculate_celsius($temperature);
    display_result($temperature, "Fahrenheit", $result, "Celsius");
}

function process_fahrenheit()
{
    $temperature = get_temperature("Celsius");
    $result = calculate_fahrenheit($temperature);
    display_result($temperature, "Celsius", $result, "Fahrenheit");
}

function get_temperature($label)
{
    echo "Enter " . $label . " temperature: ";
    $temperature = readline();
    return $temperature;
}

function calculate_celsius($fahrenheit)
{
    $celsius = ($fahrenheit - 32) * 5 / 9;
        
    return $celsius;
}

function calculate_fahrenheit($celsius)
{
    $fahrenheit = $celsius * 9 / 5 + 32;
        
    return $fahrenheit;
}

function display_result($temperature, $from_label, $result, $to_label)
{
    echo $temperature . "° " . $from_label . " is " . $result . "° " . $to_label . "\n";
}

function main()
{
    // main could either be an if-else structure or a switch-case structure

    $choice = get_choice();

    // if-else approach
    if($choice == 'C' || $choice == 'c')
    {
        process_celsius();
    }
    else if($choice == 'F' || $choice == 'f')
    {       
        process_fahrenheit();
    }
    else
    {
        echo "You must enter C to convert to Celsius or F to convert to Fahrenheit!";
    }

    // switch-case approach
    switch($choice)
    {
        case 'C':
        case 'c':
            process_celsius();
            break;
        case 'F':
        case 'f':
            process_fahrenheit();
            break;
        default:
            echo "You must enter C to convert to Celsius or F to convert to Fahrenheit!";
    }
}

main();

?>

Try It

edit

Copy and paste the code above into one of the following free online development environments or use your own PHP compiler / interpreter / IDE.

See Also

edit