Home  >  Article  >  Backend Development  >  Problem with foreach loop using & (and operator)

Problem with foreach loop using & (and operator)

伊谢尔伦
伊谢尔伦Original
2017-06-23 15:05:551833browse

foreach It is easy to modify the array unit by adding & before $value. Be careful when using reference in foreach. You can also disconnect the reference relationship immediately after processing, so that the above situation will not happen later.

foreach($arr as $value){ 
$value .= '4'; 
}

But this usage is also easy to cause errors, and it is not easy to find.
It’s more straightforward to look at the example:

<?php 
$arr = array(&#39;a&#39;,&#39;b&#39;,&#39;c&#39;); 
$arr2 = array(&#39;d&#39;, &#39;e&#39;, &#39;f&#39;); 

foreach($arr as $value){//习惯用$value或$val 
$value .= &#39;4&#39;; 
} 

//都处理完毕我们在页面模版输出,首先输出$arr2 
foreach($arr2 as $value){//习惯用$value或$val 
//echo $value; 
} 
//然后再这样输出 $arr; 
foreach($arr as $value){//习惯用$value或$val 
echo $value, "\n"; 
} 
?>

Let’s see if the output result is the same as expected. The result here is:

a4
b4
b4

The result is different from what I expected. This is the problem caused by the reference.
When foreach($arr as &$value) traverses the array to the end, the reference relationship is not broken. This is equivalent to the reference of the last unit of $value and $arr, which is $arr[2].
Going to foreach($arr2 as $value), the value of $value always changes with the value of the array unit. Since the reference relationship is not broken, the value of $arr[2] also changes accordingly. Until $arr2 is traversed, the value of $value is f, so the value of $arr[2] is also f.
At this time, the value of $arr should be:

Array 
( 
[0] => a4 
[1] => b4 
[2] => f 
)

This is different from the final output result we see. Then go to foreach($arr as $value). In the same way, the value of $arr[2] also changes with $value. When the key is 1, that is, $arr[1], $arr[2] The value also becomes the value of $arr[1], which is b4. Then when iterating to key 2, the value of $arr[2] becomes the value of $arr[2] again, which is b4. It is the result of output.
So be careful when using references in foreach. You can also disconnect the reference relationship immediately after processing, so that the above situation will not happen later.

foreach($arr as $value){ 
$value .= &#39;4&#39;; 
} 
unset($value);


The above is the detailed content of Problem with foreach loop using & (and operator). For more information, please follow other related articles on the PHP Chinese website!

Statement:
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