In daily development, the foreach traversal array using PHP is almost standard. It can be very convenient to traverse the array of key and value.
but do you really know the personality of it?
How does PHP foreach work?
The following PHP Chinese network with examples to explain the use of PHP foreach and considerations.
For example: There are the following arrays:
$array = Array (1,2,3,4,5);
Requires that each element value in the $array array be added 1
Generally, we can use the following processing methods, method one:
foreach ($array as $key = + $value) { $array [$key] = $value +1;}
You can also use the following methods, method two:
foreach ($array as & $value) { $value = $value +1;}
In general, there are no problems with these two formulations, and the results are the same. However, when we need to use $value in the next procedure, such as assigning a new value of 8 to $value, the result of Method 2 will be changed strangely.
foreach ($array as & $value) { $value = $value +1;} $value = 8;
When printing Print_r ($array), we want the output
Array ([0] = 2 [1] = 3 [2] = 4 [3] = 5 [4] = 6);
But it will actually output:
Array ([0] = 2 [1] = 3 [2] = 4 [3] = 5 [4] = 8),
In other words, the last element becomes 8.
Why is there such a situation?
In fact, the $value in method Two is a reference, and it is global, and when foreach executes, the reference to $value is still valid, which will cause any modifications to the $value outside of foreach to affect the last element in the $array.
So how do we solve this problem?
The method is very simple, since $value is still valid outside of foreach, then we can give the $value to unset after the completion of the foreach execution. The improved code is as follows:
foreach ($array as & $value) { $value = $value +1;} Unset ($value); $value = 8;
Now the program output $array the last element is 6, no longer affected by $value modification.