Php 调用引用函数(用一项替换另一项)时,foreach循环的行为异常
我遇到了PHP的foreach循环的一些奇怪行为,我无法解释。也许你能帮我 下面是一个简单的测试脚本:Php 调用引用函数(用一项替换另一项)时,foreach循环的行为异常,php,foreach,pass-by-reference,Php,Foreach,Pass By Reference,我遇到了PHP的foreach循环的一些奇怪行为,我无法解释。也许你能帮我 下面是一个简单的测试脚本: function mod(&$item){ $item["position"] = preg_replace("/[^0-9]+/","",$item["position"]); $item["count"] = 2*$item["count"]; } $items = [ ["position" => "1", "count" => 4],
function mod(&$item){
$item["position"] = preg_replace("/[^0-9]+/","",$item["position"]);
$item["count"] = 2*$item["count"];
}
$items = [
["position" => "1", "count" => 4],
["position" => "2", "count" => 3],
];
echo "before: <br>";
foreach($items as $item){
echo var_dump($item) . "<br>";
}
echo "modifying items...<br>";
foreach($items as &$item){
mod($item);
}
echo "after: <br>";
foreach($items as $item){
echo var_dump($item) . "<br>";
}
?>
似乎for循环已经在项[0]上循环了两次,但遗漏了项[1],这非常令人困惑。有人能给我解释一下这种行为吗
多谢各位 命名冲突,您会混淆php,因为一旦您使用
&
引用迭代项,而不使用引用迭代项。以下修改的测试脚本修复了您的问题:
您正在通过引用传递变量,并在下一个循环中再次使用它
尝试在第二个循环中重命名迭代变量
工作代码:
<?php
function mod(&$item){
$item["position"] = preg_replace("/[^0-9]+/","",$item["position"]);
$item["count"] = 2*$item["count"];
}
$items = [
["position" => "1", "count" => 4],
["position" => "2", "count" => 3],
];
echo "before: <br>";
foreach($items as $item){
echo var_dump($item) . "<br>";
}
echo "modifying items...<br>";
foreach($items as &$item){
mod($item);
}
echo "after: <br>";
foreach($items as $newItem){
echo var_dump($newItem) . "<br>";
}
?>
before:
/var/www/html/sggit/deb.php:15:
array (size=2)
'position' => string '1' (length=1)
'count' => int 4
/var/www/html/sggit/deb.php:15:
array (size=2)
'position' => string '2' (length=1)
'count' => int 3
modifying items...
after:
/var/www/html/sggit/deb.php:26:
array (size=2)
'position' => string '1' (length=1)
'count' => int 8
/var/www/html/sggit/deb.php:26:
array (size=2)
'position' => string '2' (length=1)
'count' => int 6
这就是为什么在循环之后取消设置byref循环变量是一种好的做法。在第二个循环后插入unset($item)
将解决问题。即使遵循链接并阅读解释,我仍然不理解确切的输出是如何产生的。为什么数组的最后一项被前一项替换?无论如何,至少这澄清了错误发生的原因。非常感谢。
<?php
function mod(&$item){
$item["position"] = preg_replace("/[^0-9]+/","",$item["position"]);
$item["count"] = 2*$item["count"];
}
$items = [
["position" => "1", "count" => 4],
["position" => "2", "count" => 3],
];
echo "before: <br>";
foreach($items as $item){
echo var_dump($item) . "<br>";
}
echo "modifying items...<br>";
foreach($items as &$item){
mod($item);
}
echo "after: <br>";
foreach($items as $newItem){
echo var_dump($newItem) . "<br>";
}
?>
before:
/var/www/html/sggit/deb.php:15:
array (size=2)
'position' => string '1' (length=1)
'count' => int 4
/var/www/html/sggit/deb.php:15:
array (size=2)
'position' => string '2' (length=1)
'count' => int 3
modifying items...
after:
/var/www/html/sggit/deb.php:26:
array (size=2)
'position' => string '1' (length=1)
'count' => int 8
/var/www/html/sggit/deb.php:26:
array (size=2)
'position' => string '2' (length=1)
'count' => int 6