Home >Backend Development >PHP Tutorial >foreach - PHP中为什么数组中可变变量可以这么用?

foreach - PHP中为什么数组中可变变量可以这么用?

WBOY
WBOYOriginal
2016-06-06 20:31:00945browse

$arr=array('a'=>'aa','b'=>'bb','c'=>'cc');
foreach($arr as $key=>$v){
$$key=$v;
}
echo $a;//aa

$$key然后变量应该是aa;但是输出a才有内容

回复内容:

$arr=array('a'=>'aa','b'=>'bb','c'=>'cc');
foreach($arr as $key=>$v){
$$key=$v;
}
echo $a;//aa

$$key然后变量应该是aa;但是输出a才有内容

眼花了吧...

<code>$key  ===> 'a'
$$key ===> $a
</code>

$v 才是 'aa'

$$这个是可变变量的用法,$$key 等价于 $a($key = 'a'),然后此时的$v又等于'aa',然后就$a = 'aa';相当于在循环体内定义一个一个$a的变量赋值了 ‘aa’。。。

$v='aa',$key ='a',$$key = $a,$key = $v 所以$a = 'aa'.

Statement:
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