Edit report at https://bugs.php.net/bug.php?id=65034&edit=1
ID: 65034 Updated by: ahar...@php.net Reported by: shark555 at gmail dot com Summary: Problem with array behavior after using reference -Status: Open +Status: Not a bug Type: Bug Package: *General Issues Operating System: Linux PHP Version: Irrelevant Block user comment: N Private report: N New Comment: Thank you for taking the time to write to us, but this is not a bug. Please double-check the documentation available at http://www.php.net/manual/ and the instructions on how to report a bug at http://bugs.php.net/how-to-report.php Per the warning at http://php.net/manual/en/control-structures.foreach.php, you should always unset() the iterator reference after the foreach to avoid this sort of issue, since PHP doesn't have block scope. Previous Comments: ------------------------------------------------------------------------ [2013-06-13 20:51:27] shark555 at gmail dot com Description: ------------ After using same name in first and third foreach script returns wrong result. Last element is changed to one just before it. As we can see it only happens if name of reference and variable used later in foreach is the same("product"). What is worse it affects every next iteration. After that it doesn't matter what is the name of helper variable. Problem affects PHP versions: 5.2, 5.3 and 5.4 at least. Different compilations by different people and companies. Possibly related to: https://bugs.php.net/bug.php?id=60450&edit=2 Test script: --------------- $products = array( array('id'=>1,'name'=>'Cheese'), array('id'=>2,'name'=>'Cake'), array('id'=>3,'name'=>'Fish'), array('id'=>4,'name'=>'Soup'), array('id'=>5,'name'=>'Pasta'), ); $i = 0; foreach($products as &$product) { $product['name'] = $product['name'].$i; $i++; } foreach($products as $p) { echo $p['name']; echo "\n"; } echo "\n"; foreach($products as $product) { echo $product['name']; echo "\n"; } echo "\n"; foreach($products as $p) { echo $p['name']; echo "\n"; } Expected result: ---------------- Cheese0 Cake1 Fish2 Soup3 Pasta4 Cheese0 Cake1 Fish2 Soup3 Pasta4 Cheese0 Cake1 Fish2 Soup3 Pasta4 Actual result: -------------- Cheese0 Cake1 Fish2 Soup3 Pasta4 Cheese0 Cake1 Fish2 Soup3 Soup3 Cheese0 Cake1 Fish2 Soup3 Soup3 ------------------------------------------------------------------------ -- Edit this bug report at https://bugs.php.net/bug.php?id=65034&edit=1