  Save up to 80 % on our Python e-learning courses. Only this week!

# Lesson 11 - For and while loops in PHP

In the previous lesson, Putting web pages together using PHP, we learned how to insert file/script contents into a PHP file. In today's lesson, we're going to talk about loops, which we'll use when working with databases in the next couple of courses.

## Loops

As you may have guessed based on its name, loops are code that repeat. When we something to happen 100 times, we surely wouldn't want to write the exact same code 100 times. That's what loops are for! There are several types of loops, we're going to talk about when and how to use them as well as make practical examples.

### The `FOR` loop

This loop has a constant number of iterations and contains a control variable (an integer) whose value changes every step. The syntax used in `FOR` loops is the following:

`for (variable; condition; command)`
• `variable` is the control variable of the loop. We set it to an initial value, which is usually `0` (you should know by now that everything starts with `0` in programming). In this type of loop, we usually write `\$i = 0`. Most people name the variable i as in `index`.
• `condition` is the condition required to perform the next step. If is not true, the loop will terminate. A condition is something like (`\$i < 10`).
• `command` defines what happens to the control variable at every step. In a nutshell, we tell it whether we want the control variable to increase or decrease in value. We use the `++` and `--` commands to do just that. These commands can also be used everywhere else outside of the loop, they increase or decrease the value of a variable by `1`.

Let's write a simple example. Most of you probably know Sheldon from The Big Bang Theory series. For those who don't - we're going to simulate a situation where he knocks on his neighbor's door. He always knocks three times and then shouts: "Penny!". Without loops, our code would look like this:

``````{PHP}
echo('Knock<br />');
echo('Knock<br />');
echo('Knock<br />');
echo('Penny!');
{/PHP}``````

Using a for loop, we no longer have to repeat ourselves:

``````{PHP}
for (\$i=0; \$i < 3; \$i++)
{
echo('Knock<br />');
}
echo('Penny!');
{/PHP}``````

The result:

localhost

The loop will run through 3 times. The first time through, `\$i` would hold a value of zero, so the loop would print "Knock" and it increment the value of `\$i`. The same goes for values 1 and 2. Once there is value three in `\$i`, the condition `\$i < 3` would no longer apply and the loop would terminate. We can omit the curly braces as we do with conditions. In this case, we don't have to use them since we only have one command in the loop. We could even replace the value of 3 with 10 in the loop's declaration. The command would be executed 10 times without us having to write anymore. As you can see, loops are very powerful tools.

Let's use our knowledge of loops to print the numbers from 1 to 10:

``````{PHP}
for (\$i = 1; \$i <= 10; \$i++)
echo(\$i . ' ');
{/PHP}``````

As you can see, the control variable has a different value in each iteration. Also, notice that this loop doesn't start with 0, we can set the start value to `1` and the end value to `10`. In programming, however, it is more common to start at 0 since array indexes start there.

Now, let's print out a simple multiplication table for the values from `1` to `10`. The only thing we would have to do is to declare a loop for the values from `1` to `10` and multiply its control variable with the desired number. It could look like this:

``````{PHP}
echo('<h1>Simple multiplication table</h1>');
echo('<table border="1"><tr>');
for (\$i = 1; \$i <= 10; \$i++)
echo('<td>' . \$i . '</td>');
echo('</tr><tr>');
for (\$i = 1; \$i <= 10; \$i++)
echo('<td>' . (\$i * 2) . '</td>');
echo('</tr><tr>');
for (\$i = 1; \$i <= 10; \$i++)
echo('<td>' . (\$i * 3) . '</td>');
echo('</tr><tr>');
for (\$i = 1; \$i <= 10; \$i++)
echo('<td>' . (\$i * 4) . '</td>');
echo('</tr><tr>');
for (\$i = 1; \$i <= 10; \$i++)
echo('<td>' . (\$i * 5) . '</td>');
echo('</tr><tr>');
for (\$i = 1; \$i <= 10; \$i++)
echo('<td>' . (\$i * 6) . '</td>');
echo('</tr><tr>');
for (\$i = 1; \$i <= 10; \$i++)
echo('<td>' . (\$i * 7) . '</td>');
echo('</tr><tr>');
for (\$i = 1; \$i <= 10; \$i++)
echo('<td>' . (\$i * 8) . '</td>');
echo('</tr><tr>');
for (\$i = 1; \$i <= 10; \$i++)
echo('<td>' . (\$i * 9) . '</td>');
echo('</tr><tr>');
for (\$i = 1; \$i <= 10; \$i++)
echo('<td>' . (\$i * 10) . '</td>');
echo('</tr></table>');
{/PHP}``````

The output:

localhost/loops

The program works just fine, but we've still written quite a lot. If you noticed that we essentially wrote the same code 10 times, you're right on the money! There is nothing stopping us from nesting loops in each other:

``````{PHP}
echo('<h1>Simple multiplication table using nested loops</h1>');
echo('<table border="1">');
for (\$j = 1; \$j <= 10; \$j++)
{
echo('<tr>');
for (\$i = 1; \$i <= 10; \$i++)
echo('<td>' . (\$i * \$j) . '</td>');
echo('</tr>');
}
echo('</table>');
{/PHP}``````

Quite a difference, huh? Obviously, we can't use the `\$i` variable in both loops since they're nested together and we cannot repeat variable names in the same scope. The variable `\$j` iterates over the values from `1` to `10`. In every iteration, the nested (inner) loop, using the `i` variable, is executed. We're already familiar with that loop, it prints the factors of a given number (variable `\$j`). We'll have to print a line break when the inner loop ends.

Let's create another program, we'll use it to demonstrate how to work with the "outer" variable. The application will be able to compute a given number with any exponent (e.g. 23).

``````{PHP}
\$a = 2; // power base
\$n = 3; // exponent

\$result = \$a;
for (\$i = 0; \$i < (\$n - 1); \$i++)
\$result = \$result * \$a;

echo("Result: \$result");
{/PHP}``````

I suppose we all know how exponents work. Just in case - `2^3 = 2 * 2 * 2`. So `a^n` will be computed like this - we multiply `\$a` with `\$a` for `n-1` times. We will also have to store the result in a variable for later use. In the very beginning, the result variable contains the value `\$a` and it grows as the loop iterates. As you can see, the variable `\$result` is normally accessible in the loop.

localhost

We could have also just used PHP's `pow()` function. In our case, we would call it sort of like this - `pow(2, 3)`. However, by computing the power ourselves, we get a deeper understanding of what can be done using `FOR` loop. Always remember that the number of iterations is constant. We shouldn't modify the control variable or assign anything to it - if we were to do that, our program could go into an infinite loop. Now to top it all off, let's have our code go into an infinite loop:

```// this code is wrong
for (\$i = 1; \$i <= 10; \$i++)
\$i = 1;```

Wonderful, our program is frozen! The loop keeps incrementing the variable `\$i` which is then set back to `1` every single time. Meaning that it will never reach value needed to terminate the loop and it will be eternal. The script will be terminated after a few seconds thanks to the time limit that is set in `php.ini`.

### The `while` loop

The `while` loop works a bit differently. It simply keeps repeating commands in its block as long as a condition is true. The syntax of the while loop is following:

```while (condition)
{
// command
}```

If it crossed your mind that we could simulate the `FOR` loop using the `while` loop, you're absolutely right Technically, `FOR` is a special case `while` loop case. The main difference is that the `while` loop is used differently. Usually, we put a function that returns a logical value (`true`/`false`) in its condition. The `FOR` loop example could be rewritten in "while loop format" like this:

``````{PHP}
\$i = 1;
while (\$i <= 10)
{
echo(\$i . ' ');
\$i++;
}
{/PHP}``````

Either way, doing this is not an appropriate way of using the `while` loop. `While` is used mostly when we're reading from a file and we don't know when it will reach the end. We'll get to reading files later on.

In the next lesson, Arrays and loops in PHP, we'll talk about using loops with arrays. We'll also introduce you to the `foreach` loop and list some important PHP functions for working with arrays. Today's code is available as a free download below the article.

Application includes source codes in language PHP

Article has been written for you by David Capka The author learned IT at the Unicorn College - a prestigious college providing education on IT and economics.