php.w3clubs.com

PHP tutorials and articles

 

“for” loops

Sometimes you want to run an operation several times, or you want to go through all the elements of an array. How do you do that? Using loops.

Loop 10 times

Let's see a simple example of a loop.

for ($i = 0; $i < 100; $i++) {
    echo "This punishment is not boring and pointless.<br />";
}

If you execute this, it will write down the sentence a hundred times. Let's see what the loop consists of.

  • The part in curly brackets is the block of code to be executed at every iteration (every time the loop "ticks").
  • The part after the word "for" in the brackets is setting up the loop properties. It consists of three expressions, divided by semi-colons.
    1. $i = 0; - this part is initializing the loop, here you can set up some variables. This part is always executed. Usually it's used to set a "counter" variable, by convention named $i
    2. $i < 100 - this part is a condition (similar to an if-else condition) that has to evaluate to TRUE, otherwise the loop stops. This is the place where usually you define the boundary condition, after which the loops is no longer executing. In the case above, we set that after 100 repetitions, the loop should exit
    3. $i++ - this part is executed at the end of every iteration. Often it simply increments the $i counter variable

More examples

Let's print the numbers from 1 to 10, using the $i counter variable that we increment on every iteration.

for ($i = 1; $i <= 10; $i++) {
    echo $i, '<br />';
}

You can use several statements in the expressions divided by semi-colons. Let's see two ways of printing the numbers from 1 to 10 ascending and descending.

$k = 10;
for ($i = 1; $i <= 10; $i++) {
    echo $i, ' -- ', ($k - $i +1), '<br />';
}

This will print something like:

1 -- 10 // $i is 1, so 10 - 1 + 1 is 10
2 -- 9 // $i is 2 and 10 - 2 + 1 is 9
3 -- 8
4 -- 7
5 -- 6
6 -- 5
7 -- 4
8 -- 3
9 -- 2
10 -- 1 // $i is 10 so 10 - 10 + 1 is 1

The same can be achieved by moving the initialization of $k inside the initialization part of the loop and moving the little calculation we had in the third expression of the loop, together with $i++. The calculation can actually be a simple decrement. This keeps the block of code simpler.

for ($i = 1, $k = 10; $i <= 10; $i++, $k--) {
    echo $i, ' -- ', $k, '<br />';
}

As you can see, when you need to do two or more things inside a for expression, you use comma as a separator.

Skipping an iteration

You can use continue to skip a step. When you use it, the rest of the code in the block is not executed. Usually you use continue conditionally. The following prints only even numbers.

for ($i = 1; $i <= 10; $i++) {
    if ($i % 2 != 0) {
        continue;
    }
    echo $i, '<br />';
}

In this example we tested $i in every loop iteration and if we discover it's not an even number, we skip the rest.

BTW, the same can be done easier, but the aim was to see how continue; works. Here's the easier solution, it shows that the increment expression doesn't necessarily need to increment only by one.

for ($i = 2; $i <= 10; $i += 2) {
    echo $i, '<br />';
}

Breaking out of the loop

You can use break; inside the body of the loop to exit at any time. Usually the break is also conditional.

//  loop ends when $i is 100
for ($i = 2; $i <= 100; $i += 2) {
    echo $i, '<br />';
    if ($i == 10) {
        // exit prematurely when $i is 10
        break;
    }
}

The result of executing this code is printing only the numbers 2, 4, 6, 8, 10.

Nested loops

You can nest loops within each other. The following example prints the multiplication table from 1 to 10.

<?php
for($i = 1; $i <= 10; $i++){
    echo '<h2>Multiplication by ', $i, '</h2>';
    for($j = 1; $j <= 10; $j++) {
        echo $i, ' * ', $j, ' = ', ($i*$j);
        echo '<br />';
    }
}
?>

Here's a demo of this script in action.

Looping through an array

Let's say we have the array $a = array(1, 3, 5, 7, 9);. Let's print all the elements.

First we need to know when the loops should end. We figure that out using the count() function which returns the number of elements in the array. Another important thing to remember is that array keys start from 0, so you loop from 0 to the number of elements minus 1.

$max = count($a);
for($i = 0; $i < $max; $i++) {
    echo $a[$i], '<br />';
}

This code will print all the elements of the $a array.

« to the PHP tutorial table of contents

Leave a Reply

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Powered by WordPress, theme by ♣w3clubs.com, based on Kubrik and Sancta Simplicitas