Home > Backend Development > PHP Tutorial > PHP foreach 摘引

PHP foreach 摘引

WBOY
Release: 2016-06-13 13:18:30
Original
896 people have browsed it

PHP foreach 引用

<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="php" name="code"><?php

$a = array(
	'str1' => 'val1',
	'str2' => 'val2',
	'str3' => 'val3',
	'str4' => 'val4',
);

$b = array(
	'str1', 
	'str2',
	'str3',
	'str4',

);

foreach ($b as &$val) {
	$val = $a[$val];
}

unset($val);

foreach ($b as $val) {
	echo "-----$b[3]";
	echo $val."\n";
}




?>
Copy after login
Copy after login

'val1','str2' => 'val2','str3' => 'val3','str4' => 'val4',);$b = array('str1', 'str2','str3','str4',);foreach ($b as &$val) {$val = $a[$val];}foreach ($b as $val) {echo "-----$b[3]";echo $val."\n";}?>
Copy after login

输出:

-----val1val1
-----val2val2
-----val3val3
-----val3val3


可以看到,因为第一个foreach 的引用最后的$[2] 引用没有关闭,所以,在第二个foreach 中已然在不断的对地址进行写操作;

通过打印$b[2] 的值,可以看出。随着foreach 的运行,$b[2] 的值在不断的改变。这就导致当foreach 运行到$b[1] 的时候,$b[2] 的值

就等于$b[1], 那么在最后一次运行时,$b[2] = $b[2] 就是的结果与$b[1] 一样了

解决方案:

使用unset () 方法将引用变量释放后再进行第二次foreach 循环。

<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="php" name="code"><?php $a = array( 'str1' => 'val1', 'str2' => 'val2', 'str3' => 'val3', 'str4' => 'val4', ); $b = array( 'str1', 'str2', 'str3', 'str4', ); foreach ($b as &$val) { $val = $a[$val]; } unset($val); foreach ($b as $val) { echo "-----$b[3]"; echo $val."\n"; } ?>
Copy after login


输出结果:

-----val4val1
-----val4val2
-----val4val3
-----val4val4

方案二(不怎么好):

<?php

$a = array(
	'str1' => 'val1',
	'str2' => 'val2',
	'str3' => 'val3',
	'str4' => 'val4',
);

$b = array(
	'str1', 
	'str2',
	'str3',
	'str4',

);

foreach ($b as &$val) {
	$val = $a[$val];
}

// unset($val);

foreach ($b as $item) {
	echo "-----$b[3]";
	echo $item."\n";
}




?>
Copy after login

 

换掉第二次foreach 中的as  后的变量,不使用被引用的变量,那么不会出现这样的情况。

输出:

-----val4val1
-----val4val2
-----val4val3
-----val4val4

 

总结: 建议在引用之后使用unset() 对其释放。

 

Related labels:
source:php.cn
Previous article: 奇怪的现象:恒量的创建过程 Next article: php 无限分门别类 树形数据 格式化
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
Latest Articles by Author
Latest Issues
Related Topics
More>
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template