1

The following piece of php code will destroy the last element of the array

<?php
$arr = array('A','B','C','D','E');
foreach ($arr as &$val) {}
foreach ($arr as $val) {}
print_r($arr);
?>

The output is:

Array
(
    [0] => A
    [1] => B
    [2] => C
    [3] => D
    [4] => D
)

The code can be fixed by calling unset($val); between the two foreach statements.

Why is the last element destroyed?

neworld
  • 7,757
  • 3
  • 39
  • 61
klang
  • 524
  • 3
  • 12

1 Answers1

5

This blogpost explains it better than I ever could. You should also check out this bug report at PHP.net.

alexn
  • 57,867
  • 14
  • 111
  • 145