Home > Backend Development > PHP Tutorial > Why does my PHP foreach loop with pass-by-reference change my array unexpectedly?

Why does my PHP foreach loop with pass-by-reference change my array unexpectedly?

Barbara Streisand
Release: 2024-11-13 10:54:02
Original
575 people have browsed it

Why does my PHP foreach loop with pass-by-reference change my array unexpectedly?

PHP Foreach Pass by Reference: Last Element Duplicating? (Bug?)

Understanding the Issue

Consider the following PHP code:

$arr = array("foo", "bar", "baz");

foreach ($arr as &$item) {}
print_r($arr);

foreach ($arr as $item) {}
print_r($arr); // $arr has changed to ["foo", "bar", "bar"]
Copy after login

After the first loop, the array is printed as expected:

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

However, after the second loop, the array changes unexpectedly:

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

Explanation

The issue arises because the first foreach loop passes $item by reference. This means that $item is an alias for the elements in the $arr array. In the first loop, no changes are made to $item or $arr.

However, the second loop passes $item by value. When the value of $item is assigned a new value in the loop, the corresponding element in $arr is also modified.

Specifically, the third element of $arr ("baz") is overwritten with the value of the second element ("bar") during the last iteration of the second loop. This explains why the last element of $arr is duplicated after the second loop.

Is It a Bug?

No, this behavior is not a bug. It is the intended behavior of foreach loops when passing variables by reference. It is important to be aware of this behavior to avoid unexpected changes in your arrays.

Debugging the Output

To help visualize the behavior, the following code adds echo statements to print the value of $item and the array $arr after each iteration of the loops:

echo "<br>";

foreach ($arr as &$item) {
    echo "Item: $item; Arr: ";
    print_r($arr);
    echo "<br>";
}

echo "<br>";

foreach ($arr as $item) {
    echo "Item: $item; Arr: ";
    print_r($arr);
    echo "<br>";
}
Copy after login

The output demonstrates how $item and $arr change during the loops, clearly illustrating the behavior described above.

The above is the detailed content of Why does my PHP foreach loop with pass-by-reference change my array unexpectedly?. 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