Strange behavior Of foreach

前端 未结 2 1657
醉梦人生
醉梦人生 2020-11-22 03:39

I think it\'s a no

2条回答
  •  死守一世寂寞
    2020-11-22 04:07

    The first foreach loop does not make any change to the array, just as we would expect. However, it does cause $v to be assigned a reference to each of $a’s elements, so that, by the time the first loop is over, $v is, in fact, a reference to $a[2].

    As soon as the second loop starts, $v is now assigned the value of each element. However, $v is already a reference to $a[2]; therefore, any value assigned to it will be copied automatically into the last element of the array!

    Thus, during the first iteration, $a[2] will become zero, then one, and then one again, being effectively copied on to itself. To solve this problem, you should always unset the variables you use in your by-reference foreach loops—or, better yet, avoid using the former altogether.

提交回复
热议问题