Look at the code and then explain it
Copy the code The code is as follows:
$array=array( 'a','b','c','d');
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, $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.
Copy code The code is as follows:
$array=array('a','b ','c','d');
foreach($array as $key=>&$val){//Use reference
//do something
}
echo $val ;//Output d
echo $kay;//Output 3
$val='e';
print_r($array);//Output Array ( [0] => a [1] => b [2] => c [3] => e )
?>
When the $val variable is referenced by &, after the execution of 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/825099.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/825099.htmlTechArticleLook at the code and explain it. Copy the code as follows: ?php $array=array('a','b ','c','d'); foreach($array as $key=$val){ //do something } echo $val;//Output d echo $kay;//Output 3 $val='.. .