PHP - foreach 循环中变量前的 &

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8769288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 05:27:44  来源:igfitidea点击:

PHP - Ampersand before the variable in foreach loop

phpforeachreference

提问by Sachin Sawant

Possible Duplicate:
Reference - What does this symbol mean in PHP?

可能的重复:
参考 - 这个符号在 PHP 中是什么意思?

I need to know why we use ampersand before the variable in foreach loop

我需要知道为什么我们在 foreach 循环中的变量之前使用&符号

foreach ($wishdets as $wishes => &$wishesarray) {
    foreach ($wishesarray as $categories => &$categoriesarray) {

    }
}

回答by Mariusz Sakowski

This example will show you the difference

这个例子会告诉你区别

$array = array(1, 2);
foreach ($array as $value) {
    $value++;
}
print_r($array); // 1, 2 because we iterated over copy of value

foreach ($array as &$value) {
    $value++;
}
print_r($array); // 2, 3 because we iterated over references to actual values of array

Check out the PHP docs for this here: http://pl.php.net/manual/en/control-structures.foreach.php

在此处查看 PHP 文档:http: //pl.php.net/manual/en/control-structures.foreach.php

回答by AlanFoster

This means it is passed by reference instead of value... IE any manipulation of the variable will affect the original. This differs to value where any modifications don't affect the original object.

这意味着它是通过引用而不是值传递的... IE 对变量的任何操作都会影响原始变量。这与任何修改都不会影响原始对象的值不同。

This is asked many times on stackoverflow.

这在stackoverflow上被多次询问。

回答by Rajat Singhal

It is used to apply changes in single instance of array to main array..

它用于将数组的单个实例中的更改应用于主数组。

As:

作为:

//Now the changes wont affect array $wishesarray

//现在更改不会影响数组 $wishesarray

foreach ($wishesarray as $id => $categoriy) {
      $categoriy++;
}
print_r($wishesarray); //It'll same as before..

But Now changes will reflect in array $wishesarray also

但现在变化也将反映在数组 $wishesarray 中

foreach ($wishesarray as $id => &$categoriy) {
      $categoriy++;
}
print_r($wishesarray); //It'll have values all increased by one..

回答by hakre

For the code in your question, there can be no specific answer given because the inner foreach loop is empty.

对于您问题中的代码,由于内部 foreach 循环为空,因此无法给出具体答案。

What I see with your code is, that the inner foreachiterates over a reference instead of the common way.

我在您的代码中看到的是,内部foreach迭代引用而不是常用方式。

I suggest you take a read of the foreachPHP Manual page, it covers all four cases:

我建议您阅读foreachPHP 手册页,它涵盖了所有四种情况:

foreach($standard as $each);

foreach($standard as &$each); # this is used in your question

$reference = &$standard;
foreach($reference as $each);

$reference = &$standard;
foreach($reference as &$each); # this is used in your question