我正在编写PHP代码来对数组中的每个值进行一些转换,然后从外部源(MySQL游标或者说另一个数组)向数组添加一些值.如果我使用foreach和引用转换数组值
<?php
$data = array('a','b','c');
foreach( $data as &$x )
$x = strtoupper($x);
$extradata = array('d','e','f');
// actually it was MySQL cursor
while( list($i,$x) = each($extradata) ) {
$data[] = strtoupper($x);
}
print_r($data);
?>
Run Code Online (Sandbox Code Playgroud)
数据被破坏了.所以我明白了
Array ( [0]=>A [1]=>B [2]=> [3]=>D [4]=>E [5] =>F )
Run Code Online (Sandbox Code Playgroud)
代替
Array ( [0]=>A [1]=>B [2]=>C [3]=>D [4]=>E [5] =>F )
Run Code Online (Sandbox Code Playgroud)
当我不使用引用和写
foreach( $data as &$x )
$x = strtoupper($x);
Run Code Online (Sandbox Code Playgroud)
当然,转换不会发生,但数据也不会被破坏,所以我得到了
Array ( [0]=>a [1]=>b [2]=>c [3]=>D [4]=>E [5] =>F …Run Code Online (Sandbox Code Playgroud)