note 75304 deleted from control-structures.foreach by tularis
| From: | tularis@php.net | Date: | Fri, 25 May 2007 23:04:26 +0000 |
| Subject: | note 75304 deleted from control-structures.foreach by tularis | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-126923@lists.php.net to get a copy of this message | ||
Note Submitter: Schraalhans Keukenmeester
----
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.)