3

Here are my arrays:

$not_wanted = array('example1', 'example2');

$from_this_array= array(

'example1'=>'value1',
'example2'=>'value2',
'should_stay'=>'value3'

)

at the end I should have

array('should_stay'=>'value3')

what I have been trying but it has a sickness

public function aaData($array){
    $aaData =array();
    foreach ($array as $key=>$item){        
        if(array_key_exists($key, $this->unset_array)){
            unset($array[$key]);
            $aaData[] = $item;
        }
    }
    var_dump($aaData);
    return $aaData;
}
1

4 Answers 4

2

One possible approach:

$not_wanted = array('example1', 'example2');
$from_this_array= array(
  'example1'=>'value1',
  'example2'=>'value2',
  'should_stay'=>'value3'
);

print_r(array_diff_key(
  $from_this_array, array_flip($not_wanted)));

Demo.

Note that array_diff is not relevant here, as it checks values, not keys. As your first ($not_wanted) array contains values, it should be flipped (turned into a hash) to use array_diff_key on it.

Sign up to request clarification or add additional context in comments.

Comments

1

Just for the record, here is the working version of your code:

function aaData($array){
    $aaData =array();
    foreach ($array as $key=>$item){        
        if(!in_array($key, $this->unset_array)){
            $aaData[$key] = $item;
        }
    }
    var_dump($aaData);
    return $aaData;
}

You used array_key_exists on the array that stores the keys that should be excluded - but in this array, they are the values, not the keys, so you need in_array() instead. Also it did not make sense to do unset() on the original array, as you will only return the modified one.

Demo

1 Comment

Yes I know was a bad approach what I was doing thanks to you as well!!
0

Just do:

foreach ($from_this_array as $key => $val) {
   if (in_array($key, $not_wanted)) {
      unset($from_this_array[$key]);
   }
}

See working demo

Comments

0
function aaData($array, $not_wanted){
  foreach ($not_wanted as $key){        

    if(isset($array[$key])){
        unset($array[$key]);
    }
}
return $array;
}

$not_wanted = array('example1', 'example2');

$array= array(

'example1'=>'value1',
'example2'=>'value2',
'should_stay'=>'value3'

);

print_r(aaData($array, $not_wanted));

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.