php foreach循环中使用引用的问题_PHP

WBOY
Release: 2016-06-01 11:58:34
Original
832 people have browsed it

看代码,再做解释
复制代码 代码如下:
$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 )
?>
 
在foreach循环中,当循环结束后,$key和$val变量都不会自动释放掉。值会被保留下来。
当foreach使用引用的情况下,会出现如下的情况,需要注意。
复制代码 代码如下:
$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 )
?>
 
当$val变量使用&引用后,当执行foreach循环结束后,$val指向了和$arrar[3]相同的内存地址。
当foreach循环结束后$val变量还是存在的,所以在foreach循环结束后改变$val的值,就相当于改变了$arrar[3]的值。

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!