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