note 108916 deleted from control-structures.foreach by googleguy
| From: | googleguy@php.net | Date: | Wed, 14 Nov 2012 22:16:36 +0000 |
| Subject: | note 108916 deleted from control-structures.foreach by googleguy | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-191938@lists.php.net to get a copy of this message | ||
Note Submitter: Andreas Otto
----
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â¦