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

If I iterate over 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 by an example:

$array = range(1,5);
foreach($array as &$element)
{
  $element *= 2;
}
print_r($array);
foreach($array as $element) { }
print_r($array);

Output:

Array ([0] => 2 [1] => 4 [2] => 6 [3] => 8 [4] => 10 )

Array ([0] => 2 [1] => 4 [2] => 6 [3] => 8 [4] => 8 )

, , , . , , $element, , $element, , .

+5
3

, $- / $. , var_dump() print_r()

array(5) {
  [0]=>
  int(2)
...
  [4]=>
  &int(2)
}

, &int(2).
$. , .

foreach($array as $element)
{
  var_dump($array);
}

, .
, ,

$array = range(1,5);
$element = &$array[4];
$element = $array[3];
// and $element = $array[4];
echo $array[4];

( ... , " "; -))

+7

:

$y = "some test";

foreach ($myarray as $y) {
    print "$y\n";
}

$y - , , " test". , , :

$y = $myarray[0];  // Not necessarily 0, just the 1st element

, , $y $myarray. $y , .

, :

$myarray = array("Test");
$a = "A string";
$y = &$a;

foreach ($myarray as $y) {
    print "$y\n";
}

$y $a , :

$y = $myarray[0];

, "Test" , $y.

+5

Here is how you could 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) { }
+1
source