为了能够直接修改循环中的数组元素,在$ value之前加上&amp ;.在这种情况下,该值将通过http://php.net/manual/en/control-structures.foreach.php的引用分配。
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
echo $value;
}
$arr = array(1, 2, 3, 4);
foreach ($arr as $value) {
echo $value;
}
在这两种情况下,它输出1234.添加&到$ value实际上呢? 任何帮助表示赞赏。谢谢!
答案 0 :(得分:6)
它表示您通过引用传递$ value。如果在foreach循环中更改$ value,则会相应地修改数组。
没有它,它将通过值传递,并且您对$ value所做的任何修改都只适用于foreach循环。
答案 1 :(得分:0)
这是对变量的引用,foreach循环中的主要用途是你可以改变$ value变量,这样数组本身也会改变。
答案 2 :(得分:0)
当您只是引用值时,您发布的情况不会发现太大差异。我能想出的最简单的例子描述了通过 value 引用变量与引用之间的差异,这是:
$a = 1;
$b = &$a;
$b++;
print $a; // 2
你会注意到$ a现在是2 - 因为$ b是指针到$ a。如果你没有在&符号前加上,$ a仍然是1:
$a = 1;
$b = $a;
$b++;
print $a; // 1
HTH
答案 3 :(得分:0)
通常,每个函数都会创建一个参数副本,并与它们一起使用,如果不返回它们,则“删除它们”(当发生这种情况时,取决于语言)。
如果运行一个&VARIABLE
作为参数的函数,这意味着你通过引用添加了该变量,实际上这个函数将能够更改该变量,即使不返回它。
答案 4 :(得分:0)
在开始学习通过参考传递的内容时,这并不明显......
这是一个例子,我希望你希望你能更清楚地了解传递价值和通过引用传递的差异......
<?php
$money = array(1, 2, 3, 4); //Example array
moneyMaker($money); //Execute function MoneyMaker and pass $money-array as REFERENCE
//Array $money is now 2,3,4,5 (BECAUSE $money is passed by reference).
eatMyMoney($money); //Execute function eatMyMoney and pass $money-array as a VALUE
//Array $money is NOT AFFECTED (BECAUSE $money is just SENT to the function eatMyMoeny and nothing is returned).
//So array $money is still 2,3,4,5
echo print_r($money,true); //Array ( [0] => 2 [1] => 3 [2] => 4 [3] => 5 )
//$item passed by VALUE
foreach($money as $item) {
$item = 4; //would just set the value 4 to the VARIABLE $item
}
echo print_r($money,true); //Array ( [0] => 2 [1] => 3 [2] => 4 [3] => 5 )
//$item passed by REFERENCE
foreach($money as &$item) {
$item = 4; //Would give $item (current element in array)value 4 (because item is passed by reference in the foreach-loop)
}
echo print_r($money,true); //Array ( [0] => 4 [1] => 4 [2] => 4 [3] => 4 )
function moneyMaker(&$money) {
//$money-array is passed to this function as a reference.
//Any changes to $money-array is affected even outside of this function
foreach ($money as $key=>$item) {
$money[$key]++; //Add each array element in money array with 1
}
}
function eatMyMoney($money) { //NOT passed by reference. ONLY the values of the array is SENT to this function
foreach ($money as $key=>$item) {
$money[$key]--; //Delete 1 from each element in array $money
}
//The $money-array INSIDE of this function returns 1,2,3,4
//Function isn't returing ANYTHING
}
?>