rewbs Posted February 19, 2007 Share Posted February 19, 2007 Hi all, As of PHP5, you can preceed the $value in a foreach statement by & to easily modify array values ( foreach ($a as $k=>&$v){...} ). I believe this works by making $v a reference to $a[$k]. Therefore modifying $v affects $a[$k]. This works as expected. However, I get interesting behaviour when modifying $a[$k]: [pre] <?php $a = array("original.0","original.1","original.2"); foreach ($a as $k=>&$v){ $a[$k] = "changed.$k"; echo "After changing \$a directly, \$v@$k is: $v \n"; } ?> [/pre] If $v is a reference to $a[$k], then modifying $a[$k] should affect $v. I would therefore expect the output: [pre]After changing $a directly, $v@0 is: changed.0 After changing $a directly, $v@1 is: changed.1 After changing $a directly, $v@2 is: changed.2 [/pre] However, the actual output is: [pre]After changing $a directly, $v@0 is: changed.0 After changing $a directly, $v@1 is: original.1 After changing $a directly, $v@2 is: original.2 [/pre] I'm using PHP 5.2.1 (cli) (built: Feb 7 2007 23:11:26). Can anyone help me understand this? Thanks! Link to comment https://forums.phpfreaks.com/topic/39109-foreach-and-references/ Share on other sites More sharing options...
btherl Posted February 19, 2007 Share Posted February 19, 2007 A normal foreach (without references) will take a copy of the input array if you modify it. Perhaps this is also what is happening here? In any case, it looks like it's not safe to mix direct array assignements with the foreach reference style. Link to comment https://forums.phpfreaks.com/topic/39109-foreach-and-references/#findComment-188397 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.