Loops

PHP has the following loop keywords: foreach, while, for, and do...while.

The foreach loop is designed to work with arrays, and works by iterating through each element in the array. You can also use it for objects, in which case it iterates over each public variable of that object.

The most basic use of foreach extracts only the values from each array element, like this:

    foreach($array as $val) {
            print $val;
    }

Here the array $array is looped through, and its values are extracted into $val. In this situation, the array keys are ignored completely, which usually makes most sense when they have been autogenerated (i.e., 0, 1, 2, 3, etc.).

You can also use foreach to extract keys, like this:

    foreach ($array as $key => $val) {
            print "$key = $val\n";
    }

When working with objects, the syntax is identical:

    <?php
            class monitor {
                    private $Brand;
                    public $Size;
                    public $Resolution;
                    public $IsFlat;

                    public function _ _construct($Brand, $Size, $Resolution,
     $IsFlat) {
                            $this->Brand = $Brand;
                            $this->Size = $Size;
                            $this->Resolution = $Resolution;
                            $this->IsFlat = $IsFlat;
                    }
            }

            $AppleCinema = new monitor("Apple", "30", "2560x1600", true);

            foreach($AppleCinema as $var => $val) {
                    print "$var = $val\n";
            }
    ?>

PHP while loops are used for executing a block of code only so long as a given condition is true. For example, this code will loop from 1 to 10, printing out values as it goes:

    <?php
            $i = 1;
            while($i <= 10) {
                    print "Number $i\n";
                    $i = $i + 1;
            }
    ?>

Notice that, again, PHP uses code blocks to represent the extent of our loop—while loops start with an opening brace ({) and finish with a closing brace (}) to tell PHP clearly which lines of code should be looped through.

Like if statements, you can put whatever conditions you choose into while loops, but it is crucial that you change the value of the condition with each loop; otherwise, the loop will execute forever.

While loops are most often used to increment a list where there is no known limit to the number of iterations of the loop. For example:

    while(there are still rows to read from a database) {
            read in a row;
            move to the next row;
    }

A more common form of loop is the for loop, which is slightly more complicated. A for loop is made up of a declaration, a condition, and an action: the declaration is where a loop-counter variable is declared and set to a starting value; the condition is where the loop-counter variable is checked against a value; and the action is what should happen at the end of each iteration to change the loop counter.

Here is how a for loop looks in PHP:

    <?php
            for ($i = 1; $i < 10; $i++) {
                    print "Number $i\n";
            }
    ?>

As you can see, the for loop has the three parts separated by semicolons. In the declaration, we set the variable $i to 1. For the condition, we have the loop execute if $i is less than 10. Finally, for the action, we add 1 to the value of $i for every loop iteration—that is, every time the loop code is executed.

When run, this script will count from 1 to 10, outputting text along the way. Note that it will not actually output Number 10 because we specify that $i must be less than 10, not less than or equal to it. Here is the output:

    Number 1
    Number 2
    Number 3
    Number 4
    Number 5
    Number 6
    Number 7
    Number 8
    Number 9

The PHP do...while construct is similar to a while loop. The difference is that the do...while loop is executed at least once. Consider the following piece of code:

    <?php
            $i = 11;
            do {
                    print "Number $i\n";
            } while ($i < 10);
    ?>

Using that code, "Number 11" will be printed before $i is compared against 10. If $i is less than 10 when checked, the loop executes again. In comparison, that same code could be written using a while loop:

    <?php
            $i = 11;
            while ($i < 10) {
                    print "Number $i\n";
            }
    ?>

The difference is that the while loop would output nothing, because it checks the value of $i before entering the loop. Therefore, do...while loops are always executed a minimum of once.

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.