fefe
fefe

Reputation: 9055

How can I filter an array on matching array keys from another array?

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

Upvotes: 3

Views: 96

Answers (4)

Eugen
Eugen

Reputation: 1386

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

Upvotes: 0

Just do:

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

See working demo

Upvotes: 0

kapa
kapa

Reputation: 78681

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

Upvotes: 1

raina77ow
raina77ow

Reputation: 106385

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.

Upvotes: 2

Related Questions