Why? about PHP array and php foreach loop [closed]

jondogs

New Member
If I iterate through an array twice, once by reference and then by value, PHP will overwrite the last value in the array if I use the same variable name for each loop. This is best illustrated through an example:\[code\]$array = range(1,5);foreach($array as &$element){ $element *= 2;}print_r($array);foreach($array as $element) { }print_r($array);\[/code\]Output:\[quote\] Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 [4] => 10 ) Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 [4] => 8 ) \[/quote\]Note that I am not looking for a fix, I am looking to understand why this is happening. Also note that it does not happen if the variable names in each loop are not each called \[code\]$element\[/code\], so I'm guessing it has to do with \[code\]$element\[/code\] still being in scope and a reference after the end of the first loop.
 
Back
Top