0

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

                        )
                  )
        )

3 Answers 3

2

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]);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

try this...

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.