I hope the following code is self-explanatory.
The original code was taken from a user contribution in php.net/manual...str-getcsv. It took me near half a day of work to finally figure out where the bug was generated.
It is completely reproducible.
The bug:
// THE BUG
$arr = array( "a", "b", "c", "d" );
foreach ( $arr as &$elem ) $elem = $elem . "1"; // bug origin
print_r( $arr );
echo "<pre>";
foreach ( $arr as $key => $elem ) echo "elem {$key} => {$elem}\n" ;
echo "</pre>";
Output:
Array
(
[0] => a1
[1] => b1
[2] => c1
[3] => d1 <--- notice this
)
elem 0 => a1
elem 1 => b1
elem 2 => c1
elem 3 => c1 <--- bug result !!!????
Workaround
// WORKAROUND
$arr = array( "a", "b", "c", "d" );
foreach ( $arr as $key => $elem ) $arr[$key] = $elem . "1"; // alternative code
print_r( $arr );
echo "<pre>";
foreach ( $arr as $key => $elem ) echo "elem {$key} => {$elem}\n" ;
echo "</pre>";
Output:
Array
(
[0] => a1
[1] => b1
[2] => c1
[3] => d1
)
elem 0 => a1
elem 1 => b1
elem 2 => c1
elem 3 => d1 <--- no bug