Programming Fundamentals/Functions/PHP

From Wikiversity
Jump to navigation Jump to search

functions.php[edit | edit source]

<?php

// This program asks the user for a Fahrenheit temperature, 
// converts the given temperature to Celsius,
// and displays the results.
//
// References:
//     https://www.mathsisfun.com/temperature-conversion.html
//     https://en.wikibooks.org/wiki/PHP_Programming

function get_fahrenheit()
{
    echo "Enter Fahrenheit temperature:\n";
    $fahrenheit = readline();
        
    return $fahrenheit;
}

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

function display_result($fahrenheit, $celsius)
{
    echo $fahrenheit . "° Fahrenheit is " . $celsius . "° Celsius";
}

function main()
{
    $fahrenheit = get_fahrenheit();
    $celsius = calculate_celsius($fahrenheit);
    display_result($fahrenheit, $celsius);
}

main();

?>

Try It[edit | edit source]

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 | edit source]