Loops: Free PHP & MySQL Tutorial

Dive deep into the world of PHP and MySQL programming, with this comprehensive tutorial covering a range of loop structures including While loops, For loops, and Foreach loops.

This exercise is excerpted from Noble Desktop’s past app development training materials and is compatible with iOS updates through 2021. To learn current skills in web development, check out our coding bootcamps in NYC and live online.

Note: These materials are provided to give prospective students a sense of how we structure our class exercises and supplementary materials. During the course, you will get access to the accompanying class files, live instructor demonstrations, and hands-on instruction.

Topics covered in this PHP & MySQL tutorial:

While loops, Do…while loops, For loops, Foreach loops, Breaking out of a loop, Continue statements

Exercise Overview

Loops are an incredibly important and often-used element of your programming tool belt. Here we’ll explore the many kinds of loops PHP has to offer.

SQL Bootcamp: Live & Hands-on, In NYC or Online, Learn From Experts, Free Retake, Small Class Sizes,  1-on-1 Bonus Training. Named a Top Bootcamp by Forbes, Fortune, & Time Out. Noble Desktop. Learn More.

While Loops

One of the simplest loops is the while loop. The basic idea of this loop is that while an expression is true, do something. For example:

while (I have more than $1) {
   Keep shopping!
}    

In this statement you’ll keep shopping as long as you have more than $1. Perhaps it’s not the wisest savings strategy, but it sure is fun!

  1. In your code editor, open loops.php from the phpclass folder.

  2. Here’s how to write a while loop in PHP. In between the <body> tags add the following bold code:

    <?php 
    
       $money = 100;
    
       while ($money > 1) {
          --$money;
          echo "I just bought something! I have $money dollars left now.<br>";
       }
    
    ?>
    

    What’s going on here?

    • First, we set $money to 100. So we’re starting off with 100 dollars.
    • Next, we say do something while $money is greater than 1.
    • --$money will decrement our money by 1. So every item we are buying costs 1 dollar.
    • Then we echo on the page that we just bought something and have xx dollars left. By putting the $money variable inside of our double quotes it will print the value of the variable to the screen.
    • Also note that we have to manually insert a <br> tag to make a line break.
  3. Save the page and then in a browser go to:

    • Mac: localhost:8888/phpclass/loops.php
    • Windows: localhost/phpclass/loops.php

    Wow, that’s a lot of shopping! Notice that we start with 100 dollars, but we do a little shopping straight away so our first echo statement says we have 99 dollars left.

  4. Switch back to your code editor.

  5. What would happen if we started off with only one dollar? Change the $money variable to 1 as shown in bold below:

    $money = 1;
    
       while ($money > 1) {
          --$money;
          echo "I just bought something! I have $money dollars left now.<br>";
       }
    
  6. Save the page and then in a browser go to:

    • Mac: localhost:8888/phpclass/loops.php
    • Windows: localhost/phpclass/loops.php

    Nothing happens! Why is this? Because we only start off with 1 dollar and we will only go shopping if we have more than 1 dollar, the while statement will not execute.

Do…while Loops

The do…while statement is a slight variation of while. The do…while statement guarantees that your code is executed at least once at the beginning and then will execute more times if the while conditional statement is true. For example:

do {
    do something
} while (you can keep doing it again if this is true)
  1. Switch back to your code editor.

  2. Delete everything between the <?php ?> tags, then enter the following bold code:

    $money = 1;
    do {
       --$money;
       echo "I just bought something! I have $money dollars left now.<br>";
    } while ($money > 1);
    
  3. Save the page and then in a browser go to:

    • Mac: localhost:8888/phpclass/loops.php
    • Windows: localhost/phpclass/loops.php

    Now you get your shopping in. The do code will fire the first time no matter what, and may or may not fire after that depending on whether the while conditional is true.

For Loops

The for loop is a bit more complicated than the while loop. Its syntax is as follows:

for (expression 1; expression 2; expression 3) {
    do something
}
  • Expression 1 is run once at the beginning of the loop.
  • Expression 2 is evaluated at the beginning of each loop and if it is true the code will continue to loop.
  • Expression 3 is run at the end of each loop.
  1. Switch back to your code editor.

  2. Delete everything between the <?php ?> tags, then enter the following bold code:

    for ($money = 100; $money > 1; --$money)
    {
        echo "I have $money dollars, so I can still shop!<br>";
    }
    
    • The first expression sets the $money variable to 100.
    • The second expression is similar to the conditional in the if statements we’ve seen before. If this second expression is true, then the loop will run. In this case the loop will run as long as $money is greater than 1.
    • The third expression will run at the end of each loop, decrementing $money by 1.

    You can see that here the for loop acts like a shorthand to the while statements we wrote earlier. Note that the three expressions are separated by semi-colons!

  3. Save the page and then in a browser go to:

    • Mac: localhost:8888/phpclass/loops.php
    • Windows: localhost/phpclass/loops.php

    You’ll see that we start off with 100 dollars and each time the loop runs we have one less.

Foreach Loops

This loop is typically used to loop through an array. The basic syntax is as follows:

foreach (someArray as someTemporaryValue) {
    do something, most typically you would output someTemporaryValue
}

So, for each element in the array, we set the value of the array item to be someTemporaryValue. We can do whatever we want between the brackets but most often we just want to display the value of the array.

  1. We’ve created an array for you. Open foreach.php from the phpclass folder.

  2. Take a moment to look through the file. We have three different types of arrays:

    • $movies: A simple indexed array containing the names of some movies.
    • $customer: A simple associative array containing some customer information.
    • $cars: A multidimensional array containing the info on some different cars.

    The foreach loop will allow us to easily display all the information contained in these arrays.

  3. Scroll to the bottom of the page and below the closing ?> tag (around line 77) make another set of <?php ?> tags. We don’t need to do this, but it visually helps to separate the code we will be writing now from the code that was provided for you.

  4. First let’s loop over the $movies array. In between the <?php ?> tags you just added, enter the following bold code:

    foreach ($movies as $value) {
       echo $value;
       echo '<br>';
    }
    

    This takes the array $movies and puts its value into the $value variable (you can call this variable anything you want). Then it echoes the $value and adds a <br> to make the output easier to read.

  5. Save the page and then in a browser go to:

    • Mac: localhost:8888/phpclass/foreach.php
    • Windows: localhost/phpclass/foreach.php

    You’ll see a list of all the movies.

  6. Next let’s output the values of the $customer array. Change the $movies array to $customer as shown in bold:

    foreach ($customer as $value) {
       echo $value;
       echo '<br>';
    }
    
  7. Save the page and then in a browser go to:

    • Mac: localhost:8888/phpclass/foreach.php
    • Windows: localhost/phpclass/foreach.php

    Now you’ll see all the customer information.

  8. Switch back to your code editor.

    What if we wanted to include the text of the labels as well? We want to output something like:

    firstName; Jeremy
    lastName; Kay
    etc..

    To do this we use a $key $value pair. This will pass both the name of the key as well as the value of the key.

  9. Modify the code as shown in bold:

    foreach ($customer as $key => $value) {
       echo "$key: $value";
       echo '<br>';
    }
    

    $key in this case becomes the name of the variable in the associative array and $value is the value of the variable.

  10. Save the page and then in a browser go to:

    • Mac: localhost:8888/phpclass/foreach.php
    • Windows: localhost/phpclass/foreach.php

    You’ll see the following:

    firstName: Jeremy
    lastName: Kay
    ID: 78
    email: jeremy@jeremy.com

  11. What if we wanted to loop through the entire $cars multidimensional array? We would simply put one foreach loop inside another. Switch back to your code editor.

  12. Take a look at the multidimensional array $cars. It contains the details of a number of nice cars. It is essentially one array that contains a bunch of smaller arrays.

  13. Delete the foreach loop and replace it with the following bold code:

    foreach ($cars as $i) {
       echo $i;    
    }
    
  14. Save the page and then in a browser go to:

    • Mac: localhost:8888/phpclass/foreach.php
    • Windows: localhost/phpclass/foreach.php

    You’ll see the following output repeated five times:

    Notice: Array to string conversion in …/htdocs/phpclass/foreach.php on line 80
     Array

    A notice tells you that you’re doing something not totally correct, but it is correct enough to let the page still execute. In this case, we are echoing $i which contains the value of the associative array that contains the individual car details. It converts the associative array to a string, which is why you see Array outputted after the notice. What we need to do now is loop through $i to output the details.

  15. Switch back to your code editor.

  16. Delete the echo $i; line and replace it with another foreach loop as shown in bold:

    foreach ($cars as $i) {
       foreach ($i as $key => $value) {
          echo "$key: $value";
       }    
    }
    

    This loops through the $i array and outputs its key and value.

  17. Save the page and then in a browser go to:

    • Mac: localhost:8888/phpclass/foreach.php
    • Windows: localhost/phpclass/foreach.php

    Wow, that’s a mess but at least we know it worked.

  18. Switch back to your code editor.

  19. Let’s add some HTML formatting so it’s a bit easier to read. Add the bold code:

    foreach ($cars as $i) {
       echo '<p>';
         foreach ($i as $key => $value) {
            echo "$key: $value";
            echo '<br>';
         }
       echo '</p>';
    }
    

    This puts each car in its own <p> tag and separates each detail with a line break.

  20. Save the page and then in a browser go to:

    • Mac: localhost:8888/phpclass/foreach.php
    • Windows: localhost/phpclass/foreach.php

    Much better.

Breaking Out of the Loop

Every now and then you may want to break out of a loop. To do that, simply put the break command in the loop.

  1. Switch back to your code editor.

  2. Open break.php from the phpclass folder.

  3. Let’s start by making a simple loop that counts down from 50. In between the <body> tags add the following code:

    <?php 
       for ($count = 50; $count > 1; --$count) {
          echo "$count <br>";    
       }
    ?>
    

    This is a simple for loop. First it sets $count to 50, then says to run as long as $count is greater than 1. At the end of each loop it decrements $count by 1.

  4. Save the page and then in a browser go to:

    • Mac: localhost:8888/phpclass/break.php
    • Windows: localhost/phpclass/break.php

    You’ll see a countdown from 50.

  5. Switch back to your code editor.

  6. We want to stop the loop when $count equals 25. Add the following bold code:

    for ($count = 50; $count > 1; --$count) {
       echo "$count <br>";    
       if ($count == 25) {
          break;
       }
    }
    

    This says, “if $count equals 25, stop the loop”.

  7. Save the page and then in a browser go to:

    • Mac: localhost:8888/phpclass/break.php
    • Windows: localhost/phpclass/break.php

    The loop stops at 25. Simple.

Continue Statements

A continue statement tells PHP to stop the execution of the current loop and continue immediately to the next iteration of the loop. So it doesn’t stop the entire loop, but just the current iteration of the loop.

As an example let’s have our loop only output even numbers.

  1. Switch back to your code editor.

  2. First delete the current if statement. The code should look as follows:

    for ($count = 50; $count > 1; --$count) {
       echo "$count <br>";    
    }
    
  3. To test whether a number is even or odd we can use the % (modulus) command. Modulus is the remainder after division. If you divide an even number by 2 then the remainder is 0. If you divide an odd number by 2 then the remainder will be 1. Add the following bold code:

    for ($count = 50; $count > 1; --$count) {
       if ($count % 2 == 1) {
          continue;
       }
       echo "$count <br>";
    }
    

    This says: “Divide $count by 2 and if the remainder is 1, then stop the current iteration of the loop and continue to the next iteration.” So if the code encounters an odd number, it won’t get to the echo statement.

  4. Save the page and then in a browser go to:

    • Mac: localhost:8888/phpclass/break.php
    • Windows: localhost/phpclass/break.php

    You’ll see a list of only even numbers.

  5. Switch back to your code editor.

  6. Close any files you may have open. We’re done with them.

How to Learn Full-Stack Web Development

Master full-stack web development with hands-on training. Build fully functional websites and applications using HTML, CSS, JavaScript, Python, and web developer tools.

Yelp Facebook LinkedIn YouTube Twitter Instagram