Edit report at https://bugs.php.net/bug.php?id=65452&edit=1
ID: 65452 Updated by: requi...@php.net Reported by: philippe at kinhelios dot com Summary: Change value in array -Status: Open +Status: Not a bug Type: Bug Package: *General Issues Operating System: Linux web1106.90.ha.ovh.net 3.2. 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 The reference persists even after the loop finishes. In the second loop, foreach will assign values to $localValue... which is still a reference to the last element in $arrayOne. The net effect is the second-to-last element overwrites the last element. (Try with three or more items in $arrayOne.) Solution: unset($localValue) after the first loop (best), or don't use it as a reference and update $arrayOne using the $localKey, or use a different variable in the second loop, or use references in the second loop. Previous Comments: ------------------------------------------------------------------------ [2013-08-14 17:23:00] philippe at kinhelios dot com Description: ------------ Hi, Note : PHP Version 5.2.17, but I can't update the version of php, it is installed on a shared server. Loop to change the values in an array by reference and then another loop but same variable name, the initial array is modified again. [translate by http://www.bing.com/translator/] Test script: --------------- <?php $arrayOne = array( 'key1' => array('k1' => 'val_key1_k1'), 'key2' => array('k1' => 'val_key2_k1') ); foreach ($arrayOne as $localKey => &$localValue) // character & $localValue['k1'] .= '_add'; // ----- print_r($arrayOne); $counter = 0; foreach ($arrayOne as $k => $localValue) // same name of variable "$localValue", but local $counter++; print_r($arrayOne); // is the same array ? => NO ! ?> Expected result: ---------------- Array ( [key1] => Array ( [k1] => val_key1_k1_add ) [key2] => Array ( [k1] => val_key2_k1_add ) ) Actual result: -------------- Array ( [key1] => Array ( [k1] => val_key1_k1_add ) [key2] => Array ( [k1] => val_key1_k1_add // Hey! My value changed here ! ) ) ------------------------------------------------------------------------ -- Edit this bug report at https://bugs.php.net/bug.php?id=65452&edit=1