在foreach循环中报告奇怪的PHP错误?

时间:2015-06-15 20:06:09

标签: php arrays foreach

我希望以下代码不言自明。

原始代码取自a user contribution in php.net/manual...str-getcsv。我花了将近半天的时间来确定错误的产生位置。

完全可以重复。

错误:

// 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>";

输出:

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 
$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>";

输出:

Array
    (
        [0] => a1
        [1] => b1
        [2] => c1
        [3] => d1
    )
elem 0 => a1
elem 1 => b1
elem 2 => c1
elem 3 => d1  <--- no bug

0 个答案:

没有答案