Edward
Edward

Reputation: 3081

PHP modify array elements during loop

I need my processing function to receive the entire original array minus 1 value which i am deleting in a loop. However the next call needs to have the original value added back and the next value removed.

The array keys are non numeric so I cannot use a for loop, because I need the key value. Below is the array i am sending to processing function().

$stuff = array(
        'inner'=>array('A=>Alpha','B=>Beta','C=>Charlie'),
        'outer'=>array('C=>Cat','D=>Dock','K=>Kite')
              );      

This is what the processing function should receive during each loop iteration.
Loop 1:  
     array(
    'inner'=>array('B=>Beta','C=>Charlie'),
    'outer'=>array('C=>Cat','D=>Dock','K=>Kite')
          )
Loop 2:  
     array(
    'inner'=>array('A=>Alpha','C=>Charlie'),
    'outer'=>array('C=>Cat','D=>Dock','K=>Kite')
          )
Loop 3: 
     array(
    'inner'=>array('A=>Alpha','B=>Beta'),
    'outer'=>array('C=>Cat','D=>Dock','K=>Kite')
          )

CODE:

Causes an infinite Loop because each value is immediately added onto the end.

 foreach($stuff as $term=>&$arr)
   {
       switch($term)
       {
         case 'inner':
          foreach($arr as $key=>$value)
           {
               //remove value
               unset($arr[$key]);
               processing($stuff);
               //add it back
               $arr[$key] = $value;
           }
         break;
       }
   }

Causes it to run an extra time:

foreach($stuff as $term=>&$arr)
       {
           switch($term)
           {
             case 'inner':
              $last_key = end(array_keys($arr));
              foreach($arr as $key=>$value)
               {
                    unset($arr[$key]);
                    processing($stuff);
                    //put it BACK
                    if($key != $last_key)
                    {
                        $arr[$key] = $value;
                    }
               }
             break;
           }
       }

What is the best approach to solving this problem?

Upvotes: 1

Views: 699

Answers (1)

mzulch
mzulch

Reputation: 1539

You can iterate through the inner items and make a new copy of the array each time, then unset the current key. With this approach you don't have to worry about adding/removing items from the original array while iterating over it.

$items = ['A', 'B', 'C'];

foreach ($items as $key => $item) {
    $otherItems = $items;
    unset($otherItems[$key]);

    print_r($otherItems);
}

Upvotes: 1

Related Questions