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

[PHP] Problems in reference assignment in foreach loop

little bottle
Release: 2023-04-05 21:54:01
forward
3369 people have browsed it

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)
*/
Copy after login

【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!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template