Is it a good idea to use unset inside a foreach?

I did something similar to this:

 foreach($model->get('data', array()) as $element)
 {
     foreach($element['user_info'] as $key => $value)
     {
          if(in_array('admin', $value)
          {
               unset($element['user_info'][$key]);
          }
     } 
 }

and I got some really nasty and unexpected results. Is there a reason for this. Is it a good idea to use unset with foreach? Care to explain? Thank you.

When deleting you need to start at the end and work backwards OR start at the beginning and stay at the beginning.

Presumably the foreach is starting at the beginning and not staying at the beginning and therefore only unsetting every second key.

Because foreach operates on a copy of the array it is safe to change or unset values inside the loop. As to your code above the first question is - what results do you expect? I don’t know if you pasted the whole code you are using - if yes then it doesn’t make much sense because you are unsetting $element’s elements while the $element is a copy of the element of the array from the outer foreach. Therefore, with each iteration of the outer foreach you are overwriting any changes to the previous $element from the previous iteration. The code doesn’t make much sense because at the end you end up with $element containing only the result of the last iteration of the main array minus the unset elements.

I think you confused PHP arrays with javascript arrays, which always have sequentially numbered keys. In PHP if you delete an array element the resulting array’s keys will not change and simply there will be a gap in the numbering sequence.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.