$somearray = array('1', 2', '3', '4');
foreach ($somearray as $value) {
$total += $value;
$value += 10;
}
When dumping the contents of $somearray after the loop, the values are not changed..... I ran into this in a few occasions while working on NucleusCMS, but didn't realize until I read doc again in PHP5:
... On each loop, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next loop, you'll be looking at the next element). ...
The key here is "assigned". When the code changes $value, it actually got overwritten and discarded in the next iteration. The loop works properly for $total or if I only read from $value.
And yes, the pitfall was pointed out in the comments.... but who reads it? Certainly I didn't.
Because of this problem, there is a second form of foreach which provides the key as well. It turns out the second form is designed to fix just this pitfall:
$somearray = array('1', 2', '3', '4');
foreach ($somearray as $key => $value) {
$total += $value;
$somearray[$key] += 10;
}
Now, the contents in the array are changed after the loop.
Someone must have thought of a better way to handle this since PHP4. There is now a solution involving reference in PHP5:
$somearray = array('1', 2', '3', '4');
foreach ($somearray as &$value) {
$total += $value;
$value += 10;
}
The result is identical to the second form of foreach loop.
Sometimes, it's just not clear of the rational behind a language feature at first, like in this case (the second form of foreach). But once you understand the reason, it's much appreciated, especially when an elegant solution comes along (the reference in foreach).
Cool, eh?