A little doubt about the reference of php array

$a=[1,2,3]; 
foreach($a as &$v){} 
foreach($a as $v){}

var_dump($a);

//
0 => int 1
1 => int 2
2 => int 2

Why did the last element become 2

Php
Jul.06,2021

this is interesting and simple. Let's analyze the execution process.

first of all, the first time is

  https://www.cnblogs.com/eleve.

trap: in the case of using the same temporary variable twice, if the first cycle uses a reference,
then the temporary variable is a reference even if the & symbol is not added in the second loop. The reference
points to the last element in the array (loops to the end of the last element).

how to avoid this problem?
1, unset ($value before the second loop)
2, use variables with different names in the second foreach, such as $item

Menu