Passingforreferenceinphp

php
zicai

One thing to watch out for when using PHP references in foreach


I’ve seen a lot of questions like this on the Nuggets in the last month:

Juejin. Cn/post / 684490… Juejin. Cn/post / 684490…

This article makes a detailed explanation of the problem, and the following is a simple reproduction of the problem:

<? The PHP $arr = [1, 2, 3]; foreach ($arr as &$item) { echo $item."\n"; } foreach ($arr as $item) { echo $item."\n"; }Copy the code

After running, the following results are displayed:

One, two, three, one, two, twoCopy the code

The final output of the second foreach is 2 instead of 3.

Explanation in the PHP documentation

The documentation shows how to avoid this problem by unsetting ($item) after foreach.

What if we don’t de-reference it?

For the first time foreach

So after the first foreach loop:

<? The PHP $arr = [1, 2, 3]; foreach ($arr as &$item) { echo $item."\n"; } echo '$item:'.$item."\n";Copy the code

We can see the result as follows:

1
2
3
$item:3
Copy the code

$arr[2] = $arr[2] = $arr[2]

<? The PHP $arr = [1, 2, 3]; foreach ($arr as &$item) { echo $item."\n"; } echo '$item:'.$item."\n"; $arr[2] = 10; echo '$item:'.$item."\n";Copy the code

The result after running is:

1
2
3
$item:3
$item:10
Copy the code

After the first foreach completes and prints $item once we modify $arr[2]=10 and print $item again to get 10, which confirms our idea

The second foreach

$item = $item = $item = $item = $item = $item = $item = $item; So the first time through the loop we not only assign $arr[0] to $item and display it, but also change the value of $arr[2] that it represents with $arr[0]. Similarly, on the second loop we assign $arr[1] to $item and display it, and at the same time change $arr[2] referenced by $item with $arr[1]. By the third loop, the changed $arr[2] is displayed.

To make it more obvious, we print $arr[2] in the second foreach:

<? The PHP $arr = [1, 2, 3]; foreach ($arr as &$item) { echo $item."\n"; {} foreach ($arr as $item) echo 'current $arr value [2] is:'. $arr [2]. "\ n"; echo $item."\n"; }Copy the code

The result of the run is:

$arr[2] = 1; $arr[2] = 2; $arr[2] = 2Copy the code

The solution

1. According to the official PHP manual, we use unset($item) to cancel the reference after the first foreach

2. We can repeat the assignment the second time by using a reference &$item

Conclusion:

Foreach assigns the current value to the $value we defined in each loop. If $value is not deleted after foreach, $value can still be used after foreach. It is a good practice to unset() defined $value and $key after each foreach for safety.