HTML and CSS Reference
In-Depth Information
The foreach loop can also process both the keys and values in an associative array if
you use slightly different syntax. Here's an example:
$synonyms = array('large' => 'big',
'loud' => 'noisy',
'fast' => 'rapid');
foreach ($synonyms as $key => $value) {
echo “$key is a synonym for $value.\n”;
}
As you can see, the foreach loop reuses the same syntax that's used to create associative
arrays.
for Loops
Use for loops when you want to run a loop a specific number of times. The loop state-
ment has three parts: a variable assignment for the loop's counter, an expression (con-
taining the index variable) that specifies when the loop should stop running, and an
expression that increments the loop counter. Here's a typical for loop:
for ($i = 1; $i <= 10; $i++)
{
echo “Loop executed $i times.\n”;
}
$i is the counter (or index variable) for the loop. The loop is executed until $i is larger
than 10 (meaning that it will run 10 times). The last expression, $i++ , adds one to $i
every time the loop executes. The for loop can also be used to process an array instead
of foreach if you prefer. You just have to reference the array in the loop statement, like
this:
$colors = array('red', 'green', 'blue');
for ($i = 0; $i < count(array); $i++) {
echo “Currently processing “ . $colors[$i] . “.\n”;
}
There are a couple of differences between this loop and the previous one. In this case, I
start the index variable at 0, and use < rather than <= as the termination condition for the
loop. That's because count() returns the size of the $colors array, which is 3, and loop
indexes start with 0 rather than 1. If I start at 0 and terminate the loop when $i is equal
to the size of the $colors array, it runs three times, with $i being assigned the values 0,
1, and 2, corresponding to the indexes of the array being processed.
21
 
Search WWH ::




Custom Search