Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page