“foreach” loops
You know about for loops, now let's see another kind - the foreach loop. It's used only to iterate over the elements of an array and cannot be used as a general-purpose iterator the way for can be.
Quick example
// define an array
$myarray = array('one', 'two', 'three');
// loop
foreach ($myarray as $tmp) {
echo $tmp, '<br />';
}
This code will print:
one
two
three
Let's see what we've got here:
- First there's the construct
foreachfollowed by something in brackets. - Then just like the
forloop we have a block of code, enclosed in curly brackets. This code is executed on every iteration. - How many iterations there would be? As many as the elements in the array being looped.
- In the parentheses after
foreachwe have the array followed by the construct "as", followed by another variable. On every iteration, the value of next element in the array will be assigned to the new variable.
In the example above, at the first iteration $tmp will have the value "one", in the second iteration, the value of $tmp will be "two", the third iteration - "three".
Note that $tmp lives after the end of the loop. After the loop $tmp will still be defined and will have the value of the last array element, in this case "three".
Access to the keys while looping
OK, so in the example above we printed out the values of the array elements, but what about their keys?
To access the keys of an array while in a loop, you can use the following variant of the foreach construct:
foreach($array as $key => $value) {...}
On every iteration $key will contain the key of the next array element, and $value will hold the value.
Let's see the example above, slightly modified to print the keys.
// define an array
$myarray = array('one', 'two', 'three');
// loop using $k (as in "key") and $v as "value"
foreach ($myarray as $k => $v) {
echo 'Key: ', $k, ', value: ', $v, '<br />';
}
This code will print:
Key: 0, value: one
Key: 1, value: two
Key: 2, value: three
Associative arrays example
So far we only used enumerated arrays, but the associative arrays can be looped over the same way.
// define an array
$myarray = array(
'name' => 'Hendrix',
'first' => 'Jimi',
'song' => 'Foxy Lady'
);
// loop using $k (as in "key") and $v as "value"
echo 'Now playing:';
foreach ($myarray as $k => $v) {
echo $k, ': ', $v, '<br />';
}
This will print:
Now playing:
name: Hendrix
first: Jimi
song: Foxy Lady
Updating the array while in the loop
This code won't change anything in the array:
$myarray = array(1, 2, 3, 4, 5);
foreach($myarray as $k => $v) {
$v = $v * 2;
}
This simply changes the $v variable, but not the value in the original array. To change the array, we can address its elements using the current key:
$myarray = array(1, 2, 3, 4, 5);
foreach($myarray as $k => $v) {
$v = $v * 2;
$myarray[$k] = $v;
}
After this code executes, you'll have an updated array that looks like this:
array(2, 4, 6, 8, 10)