Skip to content

PHP 04: Loop and Decision Structures

    The first is the decision structure.

    If, Else If, and Else

    [code]if(condition 1){
    echo "Condition 1 was true!";
    }elseif(condition 2){
    echo "Condition 2 was true!";
    echo "Condition 1 and Condition 2 were NOT true!";

    Things to note:
    1. Notice the elseif needs a condition.
    2. Notice the else does NOT get a condition.

    There are three different loop structures used in PHP. 1) The while loop, 2) the for loop, and 3) the foreach loop. Let’s look at the syntax for each of these.

    The While Loop

    [code]$i = 1; // set up the incremental variable

    echo ‘<select name="people">’;

    while($i <= 5) {

    echo "<option>$i</option>\n";



    echo ‘</select>’;[/code]

    Things to note:
    1. Notice the \n in the echo statement, this adds a line break to each loop.
    2. Notice the i++ at the end of the loop, this increments the i at the end of each loop.


    [code]<select name="people">