Why does PHP overwrite values when I iterate through this array twice (by reference, by value)

前端 未结 3 379
灰色年华
灰色年华 2020-12-11 06:47

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

3条回答
  •  佛祖请我去吃肉
    2020-12-11 07:15

    This is how you would fix this problem:

    foreach($array as &$element)
    {
        $element *= 2;
    }
    unset($element); #gets rid of the reference and cleans the var for re-use.
    
    foreach($array as $element) { }
    

提交回复
热议问题