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 to_celsius()
{
    echo "Enter Fahrenheit temperature:\n";
    $f = readline();
    $c = ($f - 32) * 5 / 9;
    echo $f . "° Fahrenheit is " . $c . "° Celsius";
}

function to_fahrenheit()
{
    echo "Enter Celsius temperature:";
    $c = readline();
    $f = $c * 9 / 5 + 32;
    echo $c . "° Celsius is " . $f . "° Fahrenheit";
}

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

    if($choice == 'C' || $choice == 'c')
    {
        to_celsius();
    }
    else if($choice == 'F' || $choice == 'f')
    {       
        to_fahrenheit();
    }
    else
    {
        echo "You must enter C to convert to Celsius or F to convert to Fahrenheit!";
    }
}

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

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

function main()
{
    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]