Programming Fundamentals/Loops/PHP

From Wikiversity
Jump to navigation Jump to search

loops.php[edit | edit source]

<?php

# This program demonstrates While, Do, and For loop counting using 
// user-designated start, stop, and increment values.
//
// References:
//     https://en.wikibooks.org/wiki/PHP_Programming

function get_value($name) {
    echo "Enter " . $name . " value:\n";
    $value = readline();
    return $value;
}

function while_loop($start, $stop, $increment) {
    echo "While loop counting from " . $start . " to " . $stop . 
        " by " . $increment . ":\n";
    $count = $start;
    while ($count <= $stop) {
        echo $count . "\n";
        $count = $count + $increment;
    }
}

function do_loop($start, $stop, $increment) {
    echo "Do loop counting from " . $start . " to " . $stop . 
        " by " . $increment . ":\n";
    $count = $start;
    do {
        echo $count . "\n";
        $count = $count + $increment;
    } while ($count <= $stop);
}

function for_loop($start, $stop, $increment) {
    echo "For loop counting from " . $start . " to " . $stop . 
        " by " . $increment . ":\n";
    for ($count = $start; $count <= $stop; $count += $increment) {
        echo $count . "\n";
    }
}

function main() {
    $start = get_value("starting");
    $stop = get_value("ending");
    $increment = get_value("increment");

    while_loop($start, $stop, $increment);
    do_loop($start, $stop, $increment);
    for_loop($start, $stop, $increment);
}

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]