Mengapakah gelung foreach PHP saya dengan rujukan lulus mengubah tatasusunan saya secara tidak dijangka?

Barbara Streisand
Lepaskan: 2024-11-13 10:54:02
asal
533 orang telah melayarinya

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"]
Salin selepas log masuk

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

Array
(
    [0] => foo
    [1] => bar
    [2] => baz
)
Salin selepas log masuk

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

Array
(
    [0] => foo
    [1] => bar
    [2] => bar
)
Salin selepas log masuk

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>";
}
Salin selepas log masuk

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

Atas ialah kandungan terperinci Mengapakah gelung foreach PHP saya dengan rujukan lulus mengubah tatasusunan saya secara tidak dijangka?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel terbaru oleh pengarang
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan