Home >Backend Development >PHP Tutorial >[PHP] Problems in reference assignment in foreach loop

[PHP] Problems in reference assignment in foreach loop

little bottle
little bottleforward
2019-04-17 13:20:313318browse

foreach($arr as &$value)
1. The reference assignment symbol & changes the current element into an address each time it loops. The $value variable is the address of the corresponding element. At the end of the loop, $value is An address pointing to the last element
2. When I loop next time and use this method foreach($arr as $value), there will be a problem; foreach will assign each element to the subsequent $value variable
3. Therefore, the logic becomes, modify each element to the last element of the original array, and the last loop will always be the result of the previous one.
4. It is best not to pass by reference, use this form $arr[$key]Change the original array, or change a variable name during the next loop


$nums=array(1,2,3);
foreach($nums as &$v){
        var_dump($v);
}
/*
int(1)
int(2)
int(3)
*/
var_dump($nums);
/*
array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  &int(3)
}
*/
foreach($nums as $v){
        var_dump($v);
}
/*
int(1)
int(2)
int(2)
*/

【Related tutorial: PHP video tutorial】 

The above is the detailed content of [PHP] Problems in reference assignment in foreach loop. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete