PHP指针和变量冲突
我有一个关于 PHP 以及指针和变量的使用的问题。
以下代码产生了我意想不到的结果:
<?php
$numbers = array('zero', 'one', 'two', 'three');
foreach($numbers as &$number)
{
$number = strtoupper($number);
}
print_r($numbers);
$texts = array();
foreach($numbers as $number)
{
$texts[] = $number;
}
print_r($texts);
?>
输出如下
Array
(
[0] => ZERO
[1] => ONE
[2] => TWO
[3] => THREE
)
Array
(
[0] => ZERO
[1] => ONE
[2] => TWO
[3] => TWO
)
请注意“TWO”在第二个数组中出现了两次。
两个 foreach 循环之间似乎存在冲突,每个循环都声明一个 $number 变量(一次通过引用,第二次通过值)。
但为什么 ?为什么它只影响第二个 foreach 中的最后一个元素?
I have a question about PHP and the use of pointers and variables.
The following code produces something I wouldn't have expected:
<?php
$numbers = array('zero', 'one', 'two', 'three');
foreach($numbers as &$number)
{
$number = strtoupper($number);
}
print_r($numbers);
$texts = array();
foreach($numbers as $number)
{
$texts[] = $number;
}
print_r($texts);
?>
The output is the following
Array
(
[0] => ZERO
[1] => ONE
[2] => TWO
[3] => THREE
)
Array
(
[0] => ZERO
[1] => ONE
[2] => TWO
[3] => TWO
)
Notice the 'TWO' appearing twice in the second array.
It seems that there is a conflict between the two foreach loops, each declaring a $number variable (once by reference and the second by value).
But why ? And why does it affect only the last element in the second foreach ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
关键是PHP没有指针。它有references,这是一个相似但不同的概念,并且有一些微妙的地方差异。
如果您使用 var_dump() 而不是 print_r(),则更容易发现:
... prints:
请注意最后一个数组项中留下的
&
符号。总而言之,每当您在循环中使用引用时,最好在最后删除它们:
...每次都会打印预期的结果。
The key point is that PHP does not have pointers. It has references, which is a similar but different concept, and there are some subtle differences.
If you use var_dump() instead of print_r(), it's easier to spot:
... prints:
Please note the
&
symbol that's left in the last array item.To sum up, whenever you use references in a loop, it's good practice to remove them at the end:
... prints the expected result every time.
即使在循环之后变量
$number
也会被初始化,您需要通过unset
来中断引用此代码可以正常工作:
http://www.php.net/manual/en/language.references.unset.php
http://uk.php.net/manual/en/control-结构.foreach.php
variable
$number
is initialized even after loop , you need to break the reference byunset
this code works properly:
http://www.php.net/manual/en/language.references.unset.php
http://uk.php.net/manual/en/control-structures.foreach.php
您应该在第一个循环后中断引用。
如文档中所述:
另外,如果您使用 var_dump() 而不是 print_r(),您会注意到第一个循环后数组的最后一个元素是一个引用:
如果您遵循 Stefan Gehrig 对问题的评论,有一个链接可以完美地解释此行为:
http://schlueters.de/blog/archives/141-References- and-foreach.html
You should break the reference after the first loop.
as stated in documentation:
Also, if you use var_dump() instead of print_r(), you'll notice that the last element of array after the first loop is a reference:
If you follow Stefan Gehrig's comments on question, there is a link that perfectly explains this behaviour:
http://schlueters.de/blog/archives/141-References-and-foreach.html