2013-05-09 46 views
-4

爲了能夠在&之前直接修改循環內的數組元素。在這種情況下,價值將從http://php.net/manual/en/control-structures.foreach.php引用分配。什麼是在PHP的foreach語句?

$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是什麼增加&至$值實際上呢? 任何幫助表示讚賞。謝謝!

+3

如何閱讀手冊條目的其餘部分? – deceze 2013-05-09 18:51:30

+1

「reference」一詞是指向http://www.php.net/manual/en/language.references.php的鏈接。閱讀。 – Gumbo 2013-05-09 18:51:49

回答

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 
} 
?> 
6

它表示您通過引用傳遞$值。如果您在foreach循環中更改$值,您的數組將相應地進行修改。

沒有它,它會通過值傳遞,無論您對$ value做什麼修改都只會在foreach循環中應用。

0

這是對變量的引用,foreach循環中的主要用途是可以更改$ value變量,以及數組本身也將更改的方式。

0

當你只是引用值時,你不會注意到你發佈的情況有很大的不同。最簡單的例子,我可以想出通過參考通過描述與引用變量的區別是:

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

你會注意到一個$現在是2 - 因爲$ b是指針爲$ a。如果你沒有前綴符號,美元將仍然是1:

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

HTH

+0

感謝您的明確示例! :) – stackoverflower 2013-05-09 19:12:19

0

通常每個函數創建其參數的副本,與他們的工作,如果你不歸還「刪除它們」(發生這種情況取決於語言)。

如果使用&VARIABLE作爲參數運行函數,這意味着您通過引用添加了該變量,事實上,即使沒有返回該變量,該函數也能夠更改該變量。