Problems using references in php foreach loop_PHP tutorial

WBOY
Release: 2016-07-13 10:25:26
Original
839 people have browsed it

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].

www.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='.. .
Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!