PHP:在作为foreach()主题的数组上使用array_splice是否会引起问题? [英] PHP: Will using array_splice on an array that's the subject of a foreach() cause problems?

查看:71
本文介绍了PHP:在作为foreach()主题的数组上使用array_splice是否会引起问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一些类似这样的PHP代码:

I am writing some PHP code that's kind of like this:

foreach($filter[1] as $reject){
        $reject_processed = preg_replace('~\s~','',strtolower($filter[1][$reject]));
        if(array_key_exists($reject_processed,$list_of_common_replacements)){
            $filter[0][] = $list_of_common_replacements[$reject_processed];
            $filter[1] = array_splice($filter[1],$reject,1)
        }

    }

应该搜索拒绝值列表(filter [1]),查找是否存在替换项,然后(如果存在)将替换项添加到良好值列表(filter [0])中,同时删除固定值拒绝列表中的值.

It's supposed to search through a list of rejected values (filter[1]), find if a replacement exists, then (if so) add the replacement to the list of good values (filter[0]) while deleting the fixed value from the reject list.

会从foreach()内部的foreach()主要对象数组中删除值,从而导致此问题吗?

Will deleting values from an array that's the main subject of a foreach(), inside the foreach(), cause problems with this?

推荐答案

否. foreach 创建该数组的副本.考虑以下代码:

No. foreach creates a copy of the array. Consider the following code:

$arr = array(1,2,3,4,5);
foreach($arr as $k=>$v) {
    if($v==1) {
        unset($arr);
    }
    echo $v;
}

即使我们在第一次迭代中取消了整个原始数组的设置,它仍然会打印 12345 .

Even though we unset the entire original array in the very first iteration, this would still print 12345.

这篇关于PHP:在作为foreach()主题的数组上使用array_splice是否会引起问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆