Programming Fundamentals/Conditions/PHP

From Wikiversity
Jump to navigation Jump to search

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 if_else()
{
    $choice = get_choice();
    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!";
    }
}

function switch_case()
{
    $choice = get_choice();
    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!";
    }
}

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($scale)
{
    echo "Enter " . $scale . " temperature:\n";
    $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, $result, $to)
{
    echo $temperature . "° " . $from . " is " . $result . "° " . $to . "\n";
}

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

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]