note 101538 added to control-structures.foreach
| From: | LM810 at osu1 dot php dot net | Date: | Thu, 23 Dec 2010 07:36:24 +0000 |
| Subject: | note 101538 added to control-structures.foreach | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-175157@lists.php.net to get a copy of this message | ||
To Mark Rose
-------------------
If you just put var_dump($foo) inside your second for loop, you will understand what is happening.
Once your first loop is finished, $bar has a reference to the third element of the array $foo.
Therefore, during the second loop, the third element is replaced with the first, then second and so
on until the second last element. Then the loop ends. Thus, you found that the third element had
been set with the value of the second last element of the array.
$foo = array('one', 'two', 'three');
foreach ($foo as &$bar)
{
// no-op
}
var_dump($foo);
foreach ($foo as $bar)
{
var_dump($foo);
}
Output:
-----------------
array(3) {
[0]=>
string(3) "one"
[1]=>
string(3) "two"
[2]=>
&string(5) "three"
}
array(3) {
[0]=>
string(3) "one"
[1]=>
string(3) "two"
[2]=>
&string(3) "one"
}
array(3) {
[0]=>
string(3) "one"
[1]=>
string(3) "two"
[2]=>
&string(3) "two"
}
array(3) {
[0]=>
string(3) "one"
[1]=>
string(3) "two"
[2]=>
&string(3) "two"
}
----
Server IP: 69.147.83.197
Probable Submitter: 128.250.80.15
----
Manual Page -- http://www.php.net/manual/en/control-structures.foreach.php
Edit -- https://master.php.net/note/edit/101538
Del: integrated -- https://master.php.net/note/delete/101538/integrated
Del: useless -- https://master.php.net/note/delete/101538/useless
Del: bad code -- https://master.php.net/note/delete/101538/bad+code
Del: spam -- https://master.php.net/note/delete/101538/spam
Del: non-english -- https://master.php.net/note/delete/101538/non-english
Del: in docs -- https://master.php.net/note/delete/101538/in+docs
Del: other reasons-- https://master.php.net/note/delete/101538
Reject -- https://master.php.net/note/reject/101538
Search -- https://master.php.net/manage/user-notes.php