-4

为了能够直接修改循环内的数组元素,在 $value 之前加上 &。在这种情况下,该值将通过来自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 实际上是做什么的?任何帮助表示赞赏。谢谢!

4

5 回答 5

6

它表示您通过引用传递 $value 。如果您在 foreach 循环中更改 $value,您的数组将相应修改。

没有它,它将按值传递,并且您对 $value 所做的任何修改都将仅适用于 foreach 循环。

于 2013-05-09T18:51:24.243 回答
0

这是对变量的引用,foreach 循环中的主要用途是您可以更改 $value 变量,这样数组本身也会更改。

于 2013-05-09T18:54:31.940 回答
0

当您只是引用值时,您不会注意到您发布的案例有太大差异。我能想出的最简单的例子来描述按引用变量与按引用引用变量的区别是:

$a = 1;
$b = &$a;
$b++;
print $a;  // 2

你会注意到 $a 现在是 2 - 因为 $b 是指向 $a 的指针。如果你没有在 & 号前加上前缀,$a 仍然是 1:

$a = 1;
$b = $a;
$b++;
print $a;  // 1

高温高压

于 2013-05-09T18:54:45.960 回答
0

通常每个函数都会创建其参数的副本,使用它们,如果你不返回它们“删除它们”(何时发生这种情况取决于语言)。

如果使用 as 参数运行一个函数,&VARIABLE这意味着您通过引用添加了该变量,实际上该函数将能够更改该变量,即使不返回它。

于 2013-05-09T18:54:57.843 回答
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
}
?>
于 2013-05-09T19:27:32.203 回答