note 28118 deleted from control-structures.foreach by sniper
| From: | sniper@php.net | Date: | Wed, 08 Oct 2003 04:06:52 +0000 |
| Subject: | note 28118 deleted from control-structures.foreach by sniper | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-58007@lists.php.net to get a copy of this message | ||
Note Submitter: rlentjes@bigpond.net.au
----
--------- Note 1 ---------
Please be aware of what happens with array copy:
$arr = array ("one", "two", "three");
next($arr);
echo "A: " . current($arr) . "\n"; // two
$arr2 = $arr;
echo "B: " . current($arr) . "\n"; // one
echo "C: " . current($arr2) . "\n"; // two
After the copy operation, the copy ($arr2) has the same position as the original ($arr) did before,
but the original ($arr) was reset!
--------- Note 2 ---------
Note that the two arrays do not seem to share the same ELEMENT POINTER as guessed at in some notes
above:
reset($arr);
end($arr2);
echo "D: " . current($arr) . "\n"; // one
echo "E: " . current($arr2) . "\n"; // three
echo "\n";
--------- Note 3 ---------
The array copy detail in Note 1 above has an effect on any use of functions like current(). Note
that the reference to $arr is the original real variable, note that foreach() modifies the original
variable's ELEMENT POINTER.
end($arr);
echo "A: " . current($arr) . "\n"; // three
foreach ($arr as $val1)
{
echo "\$val1($val1)\n";
echo "B: " . current($arr) . "\n"; // always one
foreach ($arr as $val2)
{
echo "\$val1($val1) \$val2($val2)\n";
echo "C: " . current($arr) . "\n"; // always one
}
}
The $arr internal ELEMENT POINTER was CHANGED from "three" to "one" when the
outer foreach() made a copy of $arr for its own use.
As a general note, arrays have internal iterators.
This is like a GLOBAL VARIABLE being incremented throughout the program (in the same scope as the
array, that is). So be aware of this.