foreach循环和与放大器基准; $值 [英] foreach loop and reference of &$value
问题描述
为什么空foreach循环可以改变结果。
Why is an empty foreach loop can change the result.
我有以下的code:
$variable = [1,2,3,4];
foreach ($variable as $key => &$value)
$value ++;
var_dump($variable);
结果我得到的是
array (size=4)
0 => int 2
1 => int 3
2 => int 4
3 => &int 5
现在,当我添加一个空的foreach循环像这样
Now ,when I add an empty foreach loop like this
$variable = [1,2,3,4];
foreach ($variable as $key => &$value)
$value ++;
foreach ($variable as $key => $value);
var_dump($variable);
我得到这样的:
array (size=4)
0 => int 2
1 => int 3
2 => int 4
3 => &int 4
有人可以解释我为什么当我添加第二个空循环,最后一个元素不会改变为什么有急症室;最后一个元素的盈?
can someone explain me why the last element doesn't change when I add the second empty loop, and why there is a & infront of the last element ?
推荐答案
在第一循环结束, $值
指向同一个地方 $变量[3]
(它们都指向同一个内存位置)
At the end of the first loop, $value
is pointing to the same place as $variable[3]
(they are pointing to the same location in memory):
$variable = [1,2,3,4];
foreach ($variable as $key => &$value)
$value ++;
即使在这个循环结束后, $值
仍是的指向内存中的相同位置 $引用变量[3]
,让您保存在 $值的值,每次
,这也将覆盖存储 $变量的值[3]
:
Even as this loop is finished, $value
is still a reference that's pointing to the same location in memory as $variable[3]
, so each time you store a value in $value
, this also overwrites the value stored for $variable[3]
:
foreach ($variable as $key => $value);
var_dump($variable);
通过本的foreach的每一个评价,既 $值
和 $变量[3]
正在成为等于在$变量可迭代项目的价值。
With each evaluation of this foreach, both $value
and $variable[3]
are becoming equal to the value of the iterable item in $variable.
因此,在第二循环的第三次迭代, $值
和 $变量[3]
相等4参照,那么第四和第二循环的最后一次迭代过程中,没有什么变化,因为你传递的 $变量[3]
(这仍然是<$值C $ C>&安培; $值)以 $值
(这仍然是&安培; $值
)。
So in the 3rd iteration of the second loop, $value
and $variable[3]
become equal to 4 by reference, then during the 4th and final iteration of the second loop, nothing changes because you're passing the value of $variable[3]
(which is still &$value
) to $value
(which is still &$value
).
这是非常令人困惑,但它并不甚至略有特质;它是code执行的究竟的,因为它应该。
It's very confusing, but it's not even slightly idiosyncratic; it's the code executing exactly as it should.
在此处了解详情: PHP:由参考传递
这篇关于foreach循环和与放大器基准; $值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!