PHP loops

Discussion in 'Web Design & Programming' started by RHochstenbach, Mar 8, 2011.

  1. RHochstenbach

    RHochstenbach Administrator Staff Member

    Likes Received:
    26
    Trophy Points:
    48
    One of the reasons why PHP is used with HTML code is its ability to generate output. One of these features is called a 'loop'. Basically a loop repeats a piece of code as long as a condition is met. I will now demonstrate this.

    WHILE loop
    A while loop repeats itself as long as a condition is true. In this example I will have it generate a table. Start with wrapping our WHILE loop inside a table using a border of 1px.
    Code:
    <table border="1">
    <?php
    
    ?>
    </table>
    
    We can also write it inside PHP tags:
    PHP:
    echo "<table border='1'>"// Remember the Single quotation marks!
    // The WHILE loop we're going to create in a minute
    echo "</table">;
    In this example I create variable with a number. Everytime the loop ends, it adds 10 to the variable. It keeps repeating the loop until the variable reaches 100. I'm going to create a pricing table for a store which sells books in large quantities. Each book costs $5.

    Now create the variables for the counter and the book price. Notice that we don't put the values inside quotation marks because they are numbers. Numbers don't have to be put inside quotation marks if you're going to make calculations with them.

    PHP:
    $count=10;
    $price=5;
    When that's set, we're going to start setting the WHILE loop. We first want to tell PHP that it should execute the WHILE loop as long as the variable 'count' is equal or lower than 100. We also don't need to use quotation marks here, because we are using numbers again.
    PHP:
    while($count <= 100) {
    // The repeating code for the loop here
    }
    Now we write the code for the WHILE loop itself. We calculate the price for the books by multiplying the 'count' variable with the 'price' variable and store it inside the variable 'newprice'.
    PHP:
    $newprice $count+$price;
    // Now we create a table row
    echo "<tr>";
    echo 
    "<td>".$count ."</td><td>".$newprice ."</td>";
    echo 
    "</tr>";
    // Now we add 10 to the 'count' variable
    $count $count+10;
    Our code now looks like this:
    PHP:
    $count=10;
    $price=5;
    while(
    $count <= 100) {
    $newprice $count $price;
    echo 
    "<tr>";
    echo 
    "<td>".$count ."</td><td>".$newprice ."</td>";
    echo 
    "</tr>";
    $count $count+10;
    }
    Now load the page. It will now generate a table with prices up to 100 pieces. Does it show a PHP error? Check for ending semicolons. Doesn't it show a table? Make sure you have the <table> tags present inside your code.

    Now look at the source code inside your browser. It shows an HTML table with 10 rows.

    This method is great when building a list based on the contents of a database. I will discuss this in a later lesson.

    To explain the WHILE loop as clear as possible, I've used a counter as a real life example. However if you want to make a loop based on a counter, it can be achieved using an easier method. We can use a FOR loop.

    FOR loop
    A FOR loop is great when using a counter. In the previous example for the WHILE loop, I made a counter which started at 10, incremented by 10 at the end of each loop and that repeated itself until the counter reached 100. We first define the variables again. However, because FOR loops don't require a counter to be set in advance, so in this example we only have to set the price:
    PHP:
    $price=5;
    Now we use a FOR loop:
    Code:
    for(set a counter variable; the condition for as long it has to run; the increasing amount) {
    
    }
    
    There are 3 parts in a FOR loop:
    • The counter variable: Set a variable with the start amount.
    • The condition: As long as it's true, repeat the loop
    • The increasing amount: When a loop has finished, increase the variable with this amount
    PHP:
    for($count=10$count <= 100$count += 10) {
    $newprice $count $price;
    echo 
    "<tr>";
    echo 
    "<td>".$count ."</td><td>".$newprice ."</td>";
    echo 
    "</tr>";
    }
    There you go, you've just simplified the WHILE loop using a FOR loop instead.

    If you have created an Array (which was covered in our previous lesson), you might want to list the contents of the entire array instantly. For this, we use a kind of loop called a FOREACH loop.

    FOREACH loop
    When we go back to our previous lesson about Arrays, we made a list of members and their ages for the fishing club. Let's grab that list again.
    PHP:
    $members;
    $members['john'] = "20";
    $members['frank']= "25";
    $members['sarah'] = "22";
    $members['george'] = "35";
    Now I want to have a list of each member and his/her age. We use a FOREACH loop for this.
    PHP:
    foreach($member as $name => $age) {
    echo 
    "Name:".$member ." | Age: ".$age;
    }
    As you can see above, we assign the unique value of the array (the name) to the variable 'name' and set the value (the age) to the variable 'age'. The code in the loop will output this, and then go to the 2nd item in the array. Then the 3rd and so on, until all items have been processed.

    We are now going to turn this into a nice table using this code:
    Code:
    <html>
    <body>
    <h1>Members Fishing Club</h1>
    <table border="1">
    <tr><th>Member Name</th><th>Age</th></tr>
    <?php
    $members;
    $members['john'] = "20";
    $members['frank']= "25";
    $members['sarah'] = "22";
    $members['george'] = "35";
    
    foreach($members as $name => $age) {
    echo "<tr>";
    echo "<td>".$name ."</td><td> ".$age ."</td>";
    echo "</tr>";
    }
    ?>
    </table>
    </body>
    </html>
    
    And there you go, you now have a nice table with the members of your fishing club and their ages.
     

Share This Page