Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top