foreach ($arr as $arr) {
// code
}
This may be confusing to you because your mental model of how this works is:
- PHP takes the current element out of
$arr and advances the array pointer
- it assigns the value to
$arr
- it executes
// code
- it repeats from step one
What it actually does though is this (or at least an approximate simplification of it):
- PHP starts the
foreach operation, taking the array value that is associated with $arr
- it puts this array somewhere internally, let's say a
var iterator
- it takes the current element from
var iterator and advances the iterator
- it assigns the value it took to
$arr in your script
- it executes
// code
- it repeats from step 3
In other words, it does not take the next value from $arr on every iteration, it only used this once to get the initial iterator. The actual thing that it iterates over is stored internally and is not associated with $arr anymore. That means $arr is free for other purposes in your script and PHP is happy to reuse it on each iteration. After the loop is done, the last element remains in $arr.
If you know anonymous functions, maybe this illustrates better why this works the way it works:
foreach($arr, function ($arr) {
// code
});
The implementation of such a foreach function can be simply this:
function foreach(array $array, callable $code) {
while (list(, $value) = each($array)) {
$code($value);
}
}