22
The first example creates a copy of the value, whereas the second uses a reference to the original value. So after the first foreach runs, the original array is still untouched. After the second foreach the original array could have been modified since it was handled by reference.
第一個示例創建值的副本,而第二個示例使用對原始值的引用。因此,在第一次foreach運行后,原始陣列仍未觸及。在第二個foreach之后,原始數組可能已被修改,因為它是通過引用處理的。
Some native PHP functions already work this way, such as shuffle() which rearranges the contents of your array. You'll notice that this function doesn't return an array, you just call it:
一些本機PHP函數已經以這種方式工作,例如shuffle(),它重新排列數組的內容。您會注意到此函數不會返回數組,您只需調用它:
$myArray = array('foo', 'bar', 'fizz', 'buzz');
shuffle( $myArray );
// $myArray is now shuffled
And it works its magic since it works with the array by reference rather than creating a copy of it.
它起作用,因為它通過引用與數組一起工作,而不是創建它的副本。
Then there are functions that don't pass anything by reference but rather deal with a copy of the original value, such as ucwords() which returns the new resulting string:
然后有些函數不通過引用傳遞任何東西,而是處理原始值的副本,例如ucwords(),它返回新的結果字符串:
$myString = "hello world";
$myString = ucwords( $myString );
// $myString is now capitalized
請參閱傳遞參考。