PHP坑之:foreach &

代码如下:

$a = array('a','b','c','d');
foreach ($a as &$item){};
print_r($a);
foreach ($a as $item){};
print_r($a);

输出结果:

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

问题:两次foreach什么也没做,其中一个使用了&,结果导致数组内容被改变,是为什么呢?

打印详情输出一下:

$a = array('a','b','c','d');
foreach ($a as &$item){};
print_r($a);

foreach ($a as $key => $item) {
	echo "{$key} => {$item} ";
	print_r($a);
}

输出:

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


原因及修正:

$a = array('a','b','c','d');
foreach ($a as &$item){};//此时$item指向$a[3],即'd'
print_r($a);

//php官网给出的正确做法是
//unset($item);

//foreach 下标从0到3,每次循环时取下标赋值给$key,取value赋值给$item,而$item经过上面的循环指向$a[3]
foreach ($a as $key => $item) {//每次都修改$item的值(也就是$a[3]的值)为当前下标所指的值:a,b,c;直到最后第n个和第n-1个值相等
	echo "{$key} => {$item} ";
	print_r($a);
}



你可能感兴趣的:(PHP的坑)