Edward
Edward

Reputation: 3081

PHP unsetting array in loop

I am trying to modify an existing array called field_data and delete the parent array of the key->value pair that has control == off. So in this example I would like to unset Array[1]. However it's not working, what am I doing wrong?

foreach ($field_data['0'] as &$subsection) {
foreach ($subsection as $key => $value) 
{
if($key=='Control' && $value =='OFF') 
  { echo 'match';  unset($subsection);   }
}
return $field_data;
}
Field_data
----------
    Array
        (
            [0] => Array
                (
                    [0] => Array
                        (
                            [SECTION_ID] => 
                            [Control] => ON

                    [1] => Array
                        (
                            [SECTION_ID] => 
                            [Control] => OFF

                        )
                  )
        )

Upvotes: 0

Views: 63

Answers (3)

nvsnkv
nvsnkv

Reputation: 21

I think you shouldn't modify array you're iterating. Create an array of keys to remove instead, then iterate result and unset keys

$targets = array(); 
foreach( $field_data[0] as $skey => $svalue ) {
if( array_key_exists('Control', $svalue) && $svalue['Control'] == 'OFF' ) {
    targets[] = $skey;
}

foreach($targets as $target)
{
     unset($field_data[0][$target]);
}

Upvotes: 0

staticsan
staticsan

Reputation: 30555

You're trying to remove a variable that PHP is still using, specifically the array the inner loop is looping over.

The way you're checking you don't even need the inner loop. I would do something like this:

foreach( $field_data[0] as $skey => $svalue ) {
    if( array_key_exists('Control', $svalue) && $svalue['Control'] == 'OFF' ) {
        unset($field_data[0][$skey]);
    }
}

Upvotes: 2

Moax6629
Moax6629

Reputation: 378

try this...

unset($field_data[0][$subsection]);

Upvotes: 0

Related Questions