PHP: Will using array_splice on an array that's the subject of a foreach() cause problems?

被刻印的时光 ゝ 提交于 2020-01-04 02:20:08

问题


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)
        }

    }

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.

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


回答1:


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;
}

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




回答2:


To answer the question succinctly: No.

The reason for this is that foreach works with a copy of the array, with a copy-on-write behaviour - as soon as you modify the subject array a copy is made, so it doesn't affect the loop. Because array_splice() does not rely on the current position of the array's internal pointer, it is safe to use. current(), on the other hand, is not.

I have examined this topic in depth, got very confused, and asked a question on SO which answered my confusion very well with a full explanation of how it all works underneath - which can be found here.



来源:https://stackoverflow.com/questions/11587894/php-will-using-array-splice-on-an-array-thats-the-subject-of-a-foreach-cause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!