由foreach中使用引用导致的问题

问题

看下面一段代码,如果你能够很清楚的知道结果是什么,就不需要阅读本篇文章了.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
$array = [
'name' => 'php',
'age' => 123,
];

foreach ($array as $key => &$value) {
echo "key=$key, value=$value" . "</br>";
}

echo "<br>"

foreach ($array as $key => $value) {
echo "key=$key, value=$value" . "</br>";
}
?>

正确输出如下:

1
2
3
4
5
key=name, value=php
key=age, value=123

key=name, value=php
key=age, value=php

解答

在解释产生上述结果原因之前我们先看下面一段代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
$array = [
'name' => 'php',
'age' => 123,
];

foreach ($array as $key => $value) {
echo "key=$key, value=$value" . "</br>";
}

echo "<br>"

foreach ($array as $key => $value) {
echo "key=$key, value=$value" . "</br>";
}

?>

输出结果就不用说了,下面通过一个图简单了解一下执行的过程

那么最开始的那段代码执行情况是什么样子的呢?

参考链接

php issue with looping over an array twice using foreach and passing value by reference

php issue with looping over an array twice using foreach and passing value by reference