為什麼在使用帶有參考傳遞的 foreach 迴圈時,PHP 陣列中的最後一個元素會重複?

Susan Sarandon
發布: 2024-11-14 20:19:01
原創
367 人瀏覽過

Why does the last element in a PHP array duplicate when using a foreach loop with pass-by-reference?

PHP Foreach Pass by Reference: Last Element Duplication Mystery Unveiled

Consider the following PHP code:

$arr = ["foo", "bar", "baz"];

foreach ($arr as &$item) { /* do nothing by reference */ }
print_r($arr);

foreach ($arr as $item) { /* do nothing by value */ }
print_r($arr);
登入後複製

Upon execution, it unexpectedly modifies the original array $arr, resulting in the following output:

Array
(
    [0] => foo
    [1] => bar
    [2] => baz
)
Array
(
    [0] => foo
    [1] => bar
    [2] => bar
)
登入後複製

Understanding the Behavior

After the initial foreach loop, the variable $item remains a reference to the same memory location as $arr[2]. Consequently, each iteration of the second foreach loop, which passes arguments by value, replaces the referenced value (and hence $arr[2]) with the new iteration's value.

Detailed Explanation

In the first loop:

  • $item references the value at $arr[0], which is 'foo'.
  • $item and $arr[0] both point to 'foo'.
  • This process repeats for $arr[1] and $arr[2].

At the end of the first loop, $item still points to $arr[2].

In the second loop:

  • $item is assigned the value of $arr[0], which is 'foo'.
  • $arr[2] (still referenced by $item) is also set to 'foo'.
  • This overwrites the original value of 'baz' at $arr[2].
  • The same process occurs for $arr[1], and finally, $arr[2] is assigned the value of $arr[2], which is now 'bar' due to the previous iteration.

Clarifying Misconception

This behavior is not considered a bug. It aligns with the intended behavior of references in PHP. Similar results would be observed if you used the following syntax outside of a loop:

for ($i = 0; $i < count($arr); $i++) { $item = $arr[$i]; }
登入後複製

Conclusion

When working with references in PHP, it is crucial to recognize that modifications made through the referenced variable will also affect the original value. This behavior can be leveraged effectively or avoided depending on the desired outcome.

以上是為什麼在使用帶有參考傳遞的 foreach 迴圈時,PHP 陣列中的最後一個元素會重複?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板