Home > Backend Development > PHP Tutorial > Why does using pass-by-reference in a PHP `foreach` loop modify the array after the loop ends?

Why does using pass-by-reference in a PHP `foreach` loop modify the array after the loop ends?

Susan Sarandon
Release: 2024-11-13 09:19:02
Original
459 people have browsed it

Why does using pass-by-reference in a PHP `foreach` loop modify the array after the loop ends?

PHP Foreach Pass by Reference and Array Modification

In PHP, using pass by reference in a foreach loop can lead to unexpected behavior. Consider the following code:

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

foreach ($arr as &$item) {}
// Array remains unchanged: ["foo", "bar", "baz"]

foreach ($arr as $item) {}
// Array is modified: ["foo", "bar", "bar"]
Copy after login

Why does the second loop modify the array?

In the first loop, the $item variable is passed by reference. This means that changes made to $item also affect the corresponding element in the $arr array. However, in the second loop, $item is passed by value. Thus, changes made to $item do not affect the array.

Crucially, after the first loop, $item still references the last element of $arr. When the second loop iterates over the array, each value of $item overwrites the last element of $arr because they both refer to the same memory location.

Debugging the Output

To understand the behavior, we can echo the current value of $item and recursively print the $arr array during each loop iteration.

First Loop:

foo
Array ( [0] => foo [1] => bar [2] => baz )

bar
Array ( [0] => foo [1] => bar [2] => baz )

baz
Array ( [0] => foo [1] => bar [2] => baz )
Copy after login

After the first loop, $item points to the last element of $arr.

Second Loop:

foo
Array ( [0] => foo [1] => bar [2] => foo )

bar
Array ( [0] => foo [1] => bar [2] => bar )

bar
Array ( [0] => foo [1] => bar [2] => bar )
Copy after login

As each value of $item is overwritten, it also modifies the last element of $arr.

Is it a Bug?

No, this behavior is not a bug but rather the intended behavior of pass-by-reference. It's important to understand the implications of passing variables by reference and to use it appropriately.

The above is the detailed content of Why does using pass-by-reference in a PHP `foreach` loop modify the array after the loop ends?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template