Home > Article > Backend Development > Do you really understand PHP foreach? Very clear usage examples
In daily development, using PHP's foreach to traverse arrays is almost standard. It can very conveniently traverse the keys and values of the array. But do you really understand its personality?
How to use PHP foreach?
The following PHP Chinese website uses examples to explain the usage and precautions of PHP foreach.
For example: There is the following array:
$array = array(1,2,3,4,5);
Requires the value of each element in the $array array to be increased by 1
Usually, we can use the following Processing method, method one:
foreach($array as $key => $value){ $array[$key] = $value+1; }
You can also use the following method, method two:
foreach($array as &$value){ $value = $value+1; }
Under normal circumstances, these two writing methods will not cause any problems, and the results will be the same. But when we need to use $value in the next program, such as assigning a new value of 8 to $value, the results of method 2 will change strangely.
foreach($array as &$value){ $value = $value+1; } $value = 8;
When print_r($array) is printed, we hope to 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, $value in method 2 is a reference, and it is global. When foreach is executed, the reference to $value is still valid, which will result in any reference to $value outside foreach. Modifications will affect the last element in $array.
So how to solve this problem?
The method is very simple. Since $value is still valid outside foreach, we can unset $value after foreach execution is completed. The improved code is as follows:
foreach($array as &$value){ $value = $value+1; } Unset($value); $value = 8;
Now the program outputs the last element of $array as 6, which is no longer affected by $value modification.
The above is the detailed content of Do you really understand PHP foreach? Very clear usage examples. For more information, please follow other related articles on the PHP Chinese website!