This article will introduce to you the analysis and precautions for using references in the PHP foreach loop. I hope this article will be helpful to all students.
Example
The code is as follows
代码如下 |
复制代码 |
$array=array('a','b','c','d');
foreach($array as $key=>$val){
//do something
}
echo $val;//输出d
echo $kay;//输出3
$val='e';
print_r($array);//输出Array ( [0] => a [1] => b [2] => c [3] => d )
?>
|
|
Copy code
|
$array=array('a','b','c','d');
代码如下 |
复制代码 |
$array=array('a','b','c','d');
foreach($array as $key=>&$val){//使用引用
//do something
}
echo $val;//输出d
echo $kay;//输出3
$val='e';
print_r($array);//输出Array ( [0] => a [1] => b [2] => c [3] => e )
?>
|
foreach($array as $key=>$val){
//do something
}
echo $val;//output d |
echo $kay;//output 3
$val='e';
print_r($array);//Output Array ( [0] => a [1] => b [2] => c [3] => d )
?>
In the foreach loop, when the loop ends, the $key and $val variables will not be released automatically. The value will be preserved.
When foreach uses references, the following situations will occur, which need to be paid attention to.
The code is as follows
|
Copy code
$array=array('a','b','c','d');
foreach($array as $key=>&$val){//Use reference
//do something
}
echo $val;//output d
$val='e';
print_r($array);//Output Array ( [0] => a [1] => b [2] => c [3] => e )
?>
When the $val variable is referenced using &, when the foreach loop ends, $val points to the same memory address as $arrar[3].
The $val variable still exists after the foreach loop ends, so changing the value of $val after the foreach loop ends is equivalent to changing the value of $arrar[3].
http://www.bkjia.com/PHPjc/633197.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/633197.htmlTechArticleThis article will introduce to you the analysis and precautions for using reference problems in the PHP foreach loop. I hope this article will be useful to all students. Helps. Example code is as follows Copy code ?php $array=arra...
|
|