note 108916 added to control-structures.foreach
| From: | AndreasOtto | Date: | Mon, 04 Jun 2012 16:47:08 +0000 |
| Subject: | note 108916 added to control-structures.foreach | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-188400@lists.php.net to get a copy of this message | ||
After some mind-boggling debugging I found out that walking through an array via foreach() may lead
to unexpected results if there are references pointing to elements of that array.
In the example below you wouln't expect a change between the first and the last print_r(), for
you only manipulate a copy of the array's elements ($v).
Behold this black magic:
<?php
$arr1 = array(
'r0' => array(
'f0' => 'herp',
'f1' => 'derp',
),
'r1' => array(
'f0' => 'durr',
'f1' => 'hurr',
),
);
print_r($arr1);
/* OUTPUT:
Array
(
[r0] => Array
(
[f0] => herp
[f1] => derp
)
[r1] => Array
(
[f0] => durr
[f1] => hurr
)
)
*/
$arr2 = array();
foreach(array_keys($arr1) as $k) {
$arr2[$k] = &$arr1[$k]['f1'];
}
print_r($arr2);
/* OUTPUT:
Array
(
[r0] => derp
[r1] => hurr
)
*/
foreach($arr1 as $v) {#notice: $v is a copy, not a reference!
$v['f1'] = 'potato';
}
print_r($arr1);
/* OUTPUT:
Array
(
[r0] => Array
(
[f0] => herp
[f1] => potato
)
[r1] => Array
(
[f0] => durr
[f1] => potato
)
)
*/
?>
checked versions:
PHP 5.2.6
PHP 5.3.13
I am not quite sure whether this is a bug or just an annoying side effectâ¦
----
Server IP: 69.147.83.197
Probable Submitter: 213.160.5.140
----
Manual Page -- http://www.php.net/manual/en/control-structures.foreach.php
Edit -- https://master.php.net/note/edit/108916
Del: integrated -- https://master.php.net/note/delete/108916/integrated
Del: useless -- https://master.php.net/note/delete/108916/useless
Del: bad code -- https://master.php.net/note/delete/108916/bad+code
Del: spam -- https://master.php.net/note/delete/108916/spam
Del: non-english -- https://master.php.net/note/delete/108916/non-english
Del: in docs -- https://master.php.net/note/delete/108916/in+docs
Del: other reasons-- https://master.php.net/note/delete/108916
Reject -- https://master.php.net/note/reject/108916
Search -- https://master.php.net/manage/user-notes.php