您的第二个示例仍然是预期的行为...您正在处理数组及其值的副本,而不是实际的数组值,除非您使用“通过引用”
foreach( $arr as $x => &$line){
if( preg_match("/word$/", $line)){
$line = preg_replace( "/word$/", '', $line);
$arr[$x+1] = 'word ' . $arr[$x+1];
}
}
unset($line);
注意使用 &$line 而不是 $line,在循环结束后取消设置总是最安全的
编辑
引用PHP 手册:
注意:除非数组被引用,否则 foreach 对指定数组的副本而不是数组本身进行操作。foreach 对数组指针有一些副作用。不要在 foreach 期间或之后依赖数组指针而不重置它。
编辑
我不建议在 foreach() 中使用引用,它真的很慢,在我的情况下它慢了 16 倍。添加此行的解决方案: $line = $arr[$x]; 在循环的开始,它似乎做了一些魔术,一切都如我所料
并不是真正的魔术。它只是通过键 ($x) 直接从数组中直接用 $line 覆盖通过 foreach 循环提取的 $line 的值。
YMMV,但对我来说似乎并不慢。
以下测试脚本:
$arr = range(1,9999);
$callStartTime = microtime(true);
foreach($arr as &$line) {
$line += 1;
}
unset($line);
$callEndTime = microtime(true);
$callTime = $callEndTime - $callStartTime;
echo '<br />Call time to access by reference was '.sprintf('%.4f',$callTime)." seconds<br />\n";
foreach($arr as $x => &$line) {
$line += 1;
}
unset($line);
$callEndTime = microtime(true);
$callTime = $callEndTime - $callStartTime;
echo '<br />Call time to access by reference (retrieving key as well) was '.sprintf('%.4f',$callTime)." seconds<br />\n";
$callStartTime = microtime(true);
foreach($arr as $x => $line) {
$arr[$x] += 1;
}
unset($line);
$callEndTime = microtime(true);
$callTime = $callEndTime - $callStartTime;
echo '<br />Call time and then access array element directly was '.sprintf('%.4f',$callTime)." seconds<br />\n";
$callStartTime = microtime(true);
foreach(array_keys($arr) as $x) {
$arr[$x] += 1;
}
$callEndTime = microtime(true);
$callTime = $callEndTime - $callStartTime;
echo '<br />Call time to access array_keys was '.sprintf('%.4f',$callTime)." seconds<br />\n";
返回以下时间:
Call time to access by reference was 0.0018 seconds
Call time to access by reference (retrieving key as well) was 0.0039 seconds
Call time to access key and then access array element directly was 0.0077 seconds
Call time to access array_keys was 0.0071 seconds