PHP:深入理解PHP里Foreach改变原始数组值的两种方法

问题起源于一段代码:

teamUnit 是所有的团队项目
infoList 是已经报名了的团队项目
方法目的是取所有的团队项目和已经报名信息的进行比对,通过一个双重的foreach,赋予teamUnit的报名状态(更改原始的数组值)。

            foreach ($teamUnit as $item) {
                $item['STATE'] = 0;//标识该项目的报名状态 0 未报名/ 1 已报名
                foreach ($infoList as $info) {
                    if ($item['id'] == $info['UNIT_ID']) $item['STATE'] = 1;
                }

但这个方法被老师和学长指出存在问题因为:$item为作用域为foreach的方法体内部的局部变量,但我想通过它去改变teamUnit,虽然存在质疑但是却是能够成功改变。


为什么?
经过查找找到了部分答案:
stackoverflow上的解答
php的foreach官方文档

1  foreach (array_expression as $value)
2  foreach (array_expression as $key => $value)

在官方文档中foreach有上面两种方式:
第一种:文档中写道:

The first form loops over the array given by array_expression. On each iteration, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next iteration, you’ll be looking at the next element);

每一次迭代将内部数组的指针赋值给$value,所以我之前可以通过这种方法机缘巧合的修改成功原始数组的值。
第二种:

The second form will additionally assign the current element’s key to the $key variable on each iteration.

第二种方法是每一次将当前元素的键赋给key,在多维数组中key表现为索引,然后通过索引直接改变原数组值。


为什么不推荐使用?

在stackoverflow上和官方文档上都描述到第一种是不太推荐使用的方法:

1.stackoverflow中说到:第一种本质为引用传递,并且在PHP中引用传递的使用是有争议的不建议使用;
2.官方文档中说到:第一种方式在php5中支持但容易出现错误,php7中已经将这种调用内部数组指针方法抛弃(不是第一种方法不能用了,而是其引用传递的本质发生更改):

In PHP 5, when foreach first starts executing, the internal array pointer is automatically reset to the first element of the array. This means that you do not need to call reset() before a foreach loop.
As foreach relies on the internal array pointer in PHP 5, changing it within the loop may lead to unexpected behavior.
In PHP 7, foreach does not use the internal array pointer.

总结
所以foreach更改数组值建议使用第二种方法,好了不说了,改代码去了。

猜你喜欢

转载自blog.csdn.net/define_LIN/article/details/81474855
今日推荐