This course will become read-only in the near future. Tell us at community.p2pu.org if that is a problem.

Loops


A loop is a condition that continuously runs until it's told to stop. And like most languages, PHP has a few different kinds of loops we can use. We've already seen one kind, foreach, which will take apart an array. Very useful when you start creating apps and sites with arrays. Next in line to learn, while.

This is where PHP starts to get a little more fun and dynamic.

While Loops:
syntax:

<?

while(condition)
{
    code to display or use;
}

?>

This is probably the easiest loop to learn, use, and write. If you were to decide to learn just one, learn this one!
Here's an example of how it works:

<?

$num = 1;
while($num<=10)
{
    echo "Our number is " . $num . "<br />";
    $num++;
}

?>

In english;
Our number starts at one. While it's less than or equal to 10, echo "Our number is $num". Everytime it writes this, it increases by one using the ++ operator. When $num is greater than 10, it returns false and skips the loop.
A metaphor:
You only swim when you're in the water. Once you're on land, you stop swimming.

Our while loop will look like this:

Our number is 1
Our number is 2
Our number is 3
Our number is 4
Our number is 5
Our number is 6
Our number is 7
Our number is 8
Our number is 9
Our number is 10

Play with the code, have fun, and make it your own! The best way to learn is to test it out for yourself.

Do...While Loops:
syntax:

<?

do
{
    code to display or use;
}
while(condition);

?>

Before we go on... the difference between do...while and a while loop: do...while will always execute once, then it checks to see if it should run again.
Example:

<?

$num = 1;
do
{
    $num++;
    echo "I can hold my breath for " . $num . " minutes <br />";
}
while($num<=3);

?>

This will look like:

I can hold my breath for 2 minutes
I can hold my breath for 3 minutes
I can hold my breath for 4 minutes

We can see that the result of our two while loops are similar (and can even be the same), however do...while will run atleast once, and while has a chance of never being executed.

For Loops:
A quicker way of writing a while loop that needs to be incremented, is a for loop. It's a little more complicated, but it's much quicker for you once you learn it.
syntax:

<?

for(init; the condition;, increment)
{
    code to display or use;
}

?>

init can be anything. Typically it's used for starting a counter, which was $num in our while and do...while loops. But it can be any line of code that you want executed once before the loop starts.
the condition is your condition. As long as it returns true, it will run. This was the $num<=10 in our while loop.
increment can also be anything. Usually it's the increment for init or a different counter. But it can be any line of code you wanted executed at the end of the loop.

Example:

<?

for($num=50; $num<=55; $num++)
{
    echo "I am " . $num . " years old <br />";
}

?>

This will display:

I am 50 years old
I am 51 years old
I am 52 years old
I am 53 years old
I am 54 years old
I am 55 years old

Note: Look inside the brackets of the for statement. After each of the 3 declarations, we added a semicolin. Those are vital in running the script properly.

Foreach loops:
We already went through foreach a little bit in our previous class on arrays. I'll give you some more info on it now.
syntax:

<?

foreach($array as $value)
{
    code to be displayed or used;
}

?>

First of all, foreach loops do not need a counter. It will go through an array until it reaches the end, and continue on its own.
Here's an example:

<?

$sites = array('http://unadu.com', 'http://google.com', 'http://p2pu.org');
foreach($sites as $url)
{
    echo "Check out <a href='$url' target='_blank'>" . $url . "</a><br />";
}

?>

Key note: Remember that the as between the two condition variables is very important. That is the connecting word that creates $url out of each value from $sites.
One more example of foreach and we'll be done with loops for a while (get it, for a while).

In an array, we can also set key values. Here's an examples:
$array = array('Name1' => 'Kalob', 'Name2' => 'Peter Griffin', 'Name3' => 'Darwin');
or..
$array['Name1'] = "Kalob";
$array['Name2'] = "Peter Griffin";
$array['Name3'] = "Darwin";

Both accomplish the same thing. And here is how we pull out the key and the value from the array in a foreach loop:

This is what the syntax looks like:

<?

foreach($array as $key => $value)
{
    code to be displayed or used;
}

?>

Example:

<?

$sites = array('Unadu' => 'http://www.unadu.com/', 'Google' => 'http://www.google.com/', 'p2pu' => 'http://www.p2pu.org/');
foreach($sites as $name => $url)
{
    echo "Name: " . $name . ", URL: " . $url . "<br />";
}

?>

The => operator creates a relationship between $key and $value (or $name and $url, in our example). Think of the key pointing to the value. It literally does.
Really, the only time you need to use this is if you need both the key and the value from an array.

 


Your task:

Create a new file called loops.php.
Create one of each loop. One at a time though, for testing purposes.
- for loop, while loop, do...while loop, foreach loop with keys and values, and a regular foreach loop.

Any questions can be commented below, or you can private me directly and I'll help you out with them.

Task Discussion


  • Tynanh   March 24, 2013, 8:45 p.m.

    My loops and their code here

    loops.php

  • katpal   June 24, 2012, 8:26 a.m.

    Here is my code for Loops:

    <?

     // WHILE loops.........

    $mynumb=1;

    echo nl2br("\n\n WHILE... loops <hr>");

    while ($mynumb <=20)
    {
        echo ($mynumb . "<br>");
        $mynumb++;
    }

     // DO... WHILE loops.........
     
    echo nl2br("\n\n DO ...WHILE loops <hr>");

    $numbe=1;

    do
    {
        echo ("<br> my new number is: " .$numbe . "<br>");
        $numbe ++;
    }
     while ($numbe<=5);
     
     // FOR loops.........
     
     echo nl2br("\n\n FOR... loops <hr>");
     
     for ($number=100; $number>=95; $number--)
     {
         echo  $number. ", ";
     }
     
     
     // FOREACH loops (again).........
     
     
     echo nl2br("<hr>\n\n FOREACH... loops <hr>");
     
     $websites=array("http://www.microsoft.com", "http://www.apple.com", "http://www.google.com");
     
     foreach($websites as $url)
     {
         echo ("please click here <a href='$url'> $url </a> to visit the site <br>");
        
     }
     
      // FOREACH loops (again) with key values .........
     
      $webs= array('MS' => 'http://www.microsoft.com', 'GOOGLE' => 'http://www.google.com');
      echo ("<hr>");
     
      foreach($webs as $name => $url)
      {        
        
              echo ("<br>" . array_search($name, array_keys($webs)) );
            echo ("The Company is: " . $name . " and is located <a href='$url'> here </a>");      
      }
     
    ?>

  • Asier Iturralde Sarasola   April 14, 2012, 4:25 p.m.

    Here is the code of my exercise.

  • Landon   Oct. 26, 2012, 6:38 p.m.
    In Reply To:   Asier Iturralde Sarasola   April 14, 2012, 4:25 p.m.

    I like your code.