How do I remove keys from an array which are not in another array?

For associative arrays it can be used simple key allow-list filter:

$arr = array('a' => 123, 'b' => 213, 'c' => 321); 
$allowed = array('b', 'c'); 

print_r(array_intersect_key($arr, array_flip($allowed))); 

Will return:

Array 
( 
    [b] => 213 
    [c] => 321 
)

After some clean up it was pretty clear what I needed, and this little bit sorts it out:

foreach ($second_array as $foo) {
  if (!in_array($foo->tid, $first_array)) {
    unset($second_array[$foo->tid]);
  }
}   

Since you want to filter your array (by all keys that are contained in the other array), you may use the array_filter function.

$first  = [3,4,9,11];
$second = [ 3 => 'A' , 9 => 'B' , 12 => 'C'];

$clean = array_filter($second, function($key)use($first){
            return in_array($key,$first);
          },
           ARRAY_FILTER_USE_KEY);

// $clean = [ 3 => 'A' , 9 => 'B'];

The ARRAY_FILTER_USE_KEY constant is the 3rd parameter of the function so that $key is actually the key of the $second array in the callback. This can be adjusted:

Flag determining what arguments are sent to callback (3rd argument):

ARRAY_FILTER_USE_KEY - pass key as the only argument to callback instead of the value
ARRAY_FILTER_USE_BOTH - pass both value and key as arguments to callback instead of the value

Default is 0 which will pass value as the only argument to callback instead.


You can do this:

$keys = array_map(function($val) { return $val['value']; }, $first);
$result = array_intersect_key(array_flip($keys), $second);

The array_map call will extract the value values from $first so that $keys is an array of these values. Then array_intersect_key is used to get the intersection of $keys (flipped to use the keys as values and vice versa) and the second array $second.

Tags:

Php

Arrays