For Loops in PHP

What's a Loop?(1/7)

Programming can be tough work, and sometimes it's made tougher by having to do the same thing over and over. Let's say we want to echo a list of leap years in the editor. You might think we'd have to type:

<?php
    echo 2004;
    echo 2008;
    echo 2012;
    // And so on
?>

But there's a better way!

A loop is a useful bit of code that repeats a series of instructions for you. For instance, instead of typing echo many times like we did above, we can simply use the code in the editor to the right!

Instructions

Check out the for loop in the editor. See how it echos the value for $leap, adds four to it, then repeats? Click Save & Submit Code to learn how it all works!

inedx.php

<html>
  <head>
    <title>Leap Years</title>
  </head>
  <body>
    <?php
      for ($leap = 2004; $leap < 2050; $leap = $leap + 4) {
        echo "<p>$leap</p>";
      }
    ?>
  </body>
</html>

'For' Loop Syntax(2/7)

Cool, right? Let's go through the syntax slowly, step-by-step. Here's an example that just echos the numbers 0 to 9:

<?php
for ($i = 0; $i < 10; $i++) {
    echo $i;
}
// echoes 0123456789
?>

It breaks down like this:

  1. A for loop starts with the for keyword. This tells PHP to get ready to loop!
  2. Next comes a set of parentheses (()). Inside the parentheses, we tell PHP three things, separated by semicolons (;): where to start the loop; where to end the loop; and what to do to get to the next iteration of the loop (for instance, count up by one).
  3. After the part in parentheses, the part in curly braces ({}) tells PHP what code to run for each iteration of the loop.
  4. So the above example says: "Start looping with $i at 0, stop the loop before $i gets to 10, count up by 1 each time, and for each iteration, echo the current value of $i."

($i++ is shorthand for $i = $i + 1. You'll see this a lot!)

Instructions

Complete the for loop in the editor by replacing the ___s with the correct loop syntax. Use the example in the instructions as a guide!

Hint

Make sure to replace all _s with the correct syntax! You can use the example in the instructions as a guide.

inedx.php

<html>
  <head>
    <title>For Loops</title>
  </head>
  <body>
    <p>
      <?php

      // Echoes the first five even numbers
        for ($i = 2; $i < 11; $i = $i + 2){
            echo $i;
        }
      ?>
    </p>
  </body>
</html>

Writing Your First 'For' Loop(3/7)

Great work! Now let's put together our first for loop from start to finish.

A for loop that prints out the numbers 1 through 10 might look something like this:

for ($i = 0; $i < 11; $i++) {
    echo $i;
}

This for loop counts up by 1 each time, all the way to 10.

You could change the third part of the for loop so that it counts up by 5 instead, like this:

for ($i = 0; $i < 11; $i = $i + 5) {
    echo $i;
}

Instead of $i++, we have $i = $i + 5 to count up by 5, all the way to 10.

Instructions

Write a for loop that counts up by 10, all the way to 100 (e.g. 10, 20, 30...). Inside the for loop, echo the current value of$i, just like in the examples above.

Hint

Your code should look something like this:

for ($i = 0; $i < 101; $i = $i + 10) {
    echo $i;
}

Be very careful when constructing your loop—in particular, make sure your loop is written with conditions that will allow it to end!

For instance, if you type $i + 1 instead of $i++ or $i = $i + 1 for the third bit of your for loop, the $i variable will never actually get updated, and your loop will go on forever. This is called an infinite loop and it will cause you to have to refresh the page. Beware!

inedx.php

<html>
  <head>
    <title>Solo For Loop!</title>
  </head>
  <body>
    <p>
      <?php
     for ($i = 0; $i < 101; $i = $i + 10) {
        echo $i; // Write your for loop below!
     }
      ?>
    </p>
  </body>
</html>

When to Use 'For'(4/7)

Great job! for loops are great for running the same code over and over, especially when you know ahead of time how many times you'll need to loop. (There are other kinds, such as while and do/while loops, that we can use when we don't know ahead of time how many times we'll need to loop, but we'll cover those in a later lesson.)

There's also a special kind of loop called a foreach loop that we can use to update or print out every element in a list—for example, an array. Let's cover foreach next!

Instructions Click "Save & Submit Code" to continue.

inedx.php

<html>
  <head>
    <title>Solo For Loop!</title>
  </head>
  <body>
    <p>
      <?php
     for ($i = 0; $i < 101; $i = $i + 10) {
        echo $i; // Write your for loop below!
     }
      ?>
    </p>
  </body>
</html>

Loops + Arrays = ForEach(5/7)

The foreach loop is used to iterate over each element of an object—which makes it perfect for use with arrays!

You can think of foreach as jumping from element to element in the array and running the code between {}s for each of those elements.

Instructions

Check out the code in the editor. See how the $lang variable takes on the value of each of the elements in $langs, one by one, then echos that element to the page?

Click Save & Submit Code to learn how it all works!

inedx.php

<html>
  <head>
    <link rel="stylesheet" href="stylesheet.css" />
    <title>Codecademy Languages</title>
  </head>
  <body>
    <h1>Languages you can learn on Codecademy:</h1>
    <div class="wrapper">
      <ul>
        <?php
          $langs = array("JavaScript",
          "HTML/CSS", "PHP",
          "Python", "Ruby");

          foreach ($langs as $lang) {
              echo "<li>$lang</li>";
          }

          unset($lang);
        ?>
      </ul>
    </div>
  </body>
</html>

Practicing with ForEach(6/7)

Let's walk through the foreach syntax step-by-step. First, here's a foreach loop that iterates over an array and prints out each element it finds:

<?php
  $numbers = array(1, 2, 3);

  foreach($numbers as $item) {
      echo $item;
  }
?>

First, we create our array using the array() syntax we learned in the last lesson.

Next, we use the foreach keyword to start the loop, followed by parentheses. (This is very similar to what we've done with for loops.)

Between the parentheses, we use the $numbers as $item) syntax to tell PHP: "For each thing in $numbers, assign that thing temporarily to the variable $item." (We don't have to use the name $item—just as with for loops, we can call our temporary variable anything we want.)

Finally, we put the code we want to execute between the curly braces. In this case, we just echo each element in turn.

Instructions

Complete the foreach loop in the editor by replacing the ___s with the correct loop syntax. Use the example in the instructions as a guide!

Hint

Make sure to replace all _s with the correct syntax! You can use the example in the instructions as a guide.

inedx.php

<html>
  <head>
    <title></title>
  </head>
  <body>
    <p>
      <?php
        $sentence = array("I'm ", "learning ", "PHP!");

        foreach ($sentence as $word){
          echo $word;
        }
      ?>
    </p>
  </body>
</html>

All On Your Own!(7/7)

Great work! Now let's see you write a foreach loop all on your own.

Instructions

On line 8, there's an array named $yardlines. Write a foreach loop that iterates over the array and echos each element to the page.

Hint

Here's a foreach loop that iterates over an array named $numbers and echos each element to the page:

<?php
  $numbers = array(1, 2, 3);

  foreach($numbers as $item) {
      echo $item;
  }
?>

inedx.php

<html>
  <head>
    <title></title>
  </head>
  <body>
    <p>
      <?php
        $yardlines = array("The 50... ", "the 40... ","the 30... ", "the 20... ", "the 10... ");
        foreach($yardlines as $item) {
           echo $item;
        } // Write your foreach loop below this line


        // Write your foreach loop above this line
        echo "touchdown!";
      ?>
    </p>
  </body>
</html>