2021-04-22

一个关于PHP循环输出数组引用赋值的面试题

题目描述:有一个数组$arr = [‘a’, ‘b’, ‘c’];经过下面的循环以后$arr的结果是怎样的?

$arr = ['a','b','c'];
foreach($arr as $k=>$v){
	$v = &$arr[$k];
}

输出结果

Array
(
    [0] => b
    [1] => c
    [2] => c
)

先看一个简单的引用赋值

$x = 10;
$y = & $x;
echo $x . ',' . $y;
echo '<br/>';
$y = 20;
echo $x . ',' . $y;

输出结果

10,10
20,20

现在来看开始的题目就简单了
第一次循环:
$k => 0
$v => ‘a’
$arr = [‘a’, ‘b’, ‘c’]
$v = &$arr[0]; //$v 引用 ‘a’的地址
第二次循环:
$k => 1
$arr = [‘a’, ‘b’, ‘c’]
$v => ‘b’ //此时$v的值变了,所以 ‘a’原来的地址值变’b’了
此时$arr = [‘b’, ‘b’, ‘c’]
$v = &$arr[1];
第三次循环:
$k => 2
$arr = [‘b’, ‘b’, ‘c’]
$v => ‘c’ //此时$v的值变了,所以 ‘b’原来的地址值变’c’了
此时$arr = [‘b’, ‘c’, ‘c’]
$v = &$arr[2];

发表回复

Your email address will not be published. Required fields are marked *