Programming Fundamentals/Loops/PHP

From Wikiversity
Jump to navigation Jump to search

loops.php[edit]

<?php

// This program displays a temperature conversion table showing Fahrenheit
// temperatures from 0 to 100, in increments of 10, and the corresponding 
// Celsius temperatures using While, For, and Do loops.
//
// References:
//     https://www.mathsisfun.com/temperature-conversion.html
//     https://en.wikibooks.org/wiki/PHP_Programming

function while_loop()
{
    $f = 0;
    echo "F°    C°", "\n";
    while ($f <= 100) 
    {
        $c = ($f - 32) * 5 / 9;
        $line = $f . " = " . $c;
        echo $line, "\n";
        $f += 10;
    }
}

function for_loop()
{
    echo "F°    C°", "\n";
    for ($f = 0 ; $f <= 100 ; $f += 10) 
    {
        $c = ($f - 32) * 5 / 9;
        $line = $f . " = " . $c;
        echo $line, "\n";
    }
}

function do_loop()
{
    echo "F°    C°", "\n";
    $f = 0;
    do 
    {
        $c = ($f - 32) * 5 / 9;
        $line = $f . " = " . $c;
        echo $line, "\n";
        $f += 10;
    } while ($f <= 100);
}

function main()
{
    while_loop();
    for_loop();
    do_loop();
}

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]