note 75304 added to control-structures.foreach
| From: | SchraalhansKeukenmeester at osu1 dot php dot net | Date: | Wed, 23 May 2007 08:39:36 +0000 |
| Subject: | note 75304 added to control-structures.foreach | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-126837@lists.php.net to get a copy of this message | ||
The documentation states foreach uses a copy of an array unless it's referenced. The example
uses
foreach ($arr as &$element) {
if (condition) {
change element;
}
}
One reason never to modify array values directly in a foreach:
$arr = array (1,3,5,8,11,19);
foreach ($arr as $key=>$value) {
if ($value %2 != 0) $arr['oddcount'] += 1;
}
echo $arr['oddcount'];
//output: 5, as expected.
But:
$arr = array (1,3,5,8,11,19);
$ref = &$arr; // create a reference, outside the loop.
foreach ($arr as $key=>$value) {
if ($value %2 != 0) $arr['oddcount'] += 1;
}
echo $arr['oddcount'];
//output: 6 !!!
Since it isn't always clear where in the code a reference is made to the array, the behaviour
of any foreach loop modifying array elements directly becomes unpredictable. If you want to change
array values inside a foreach, create your own array and copy it back after the loop. (Thanks to
Gosha Bine.)
----
Server IP: 83.137.20.120
Probable Submitter: 88.211.177.163
----
Manual Page -- http://www.php.net/manual/en/control-structures.foreach.php
Edit -- https://master.php.net/note/edit/75304
Del: integrated -- https://master.php.net/note/delete/75304/integrated
Del: useless -- https://master.php.net/note/delete/75304/useless
Del: bad code -- https://master.php.net/note/delete/75304/bad+code
Del: spam -- https://master.php.net/note/delete/75304/spam
Del: non-english -- https://master.php.net/note/delete/75304/non-english
Del: in docs -- https://master.php.net/note/delete/75304/in+docs
Del: other reasons-- https://master.php.net/note/delete/75304
Reject -- https://master.php.net/note/reject/75304
Search -- https://master.php.net/manage/user-notes.php