1

I want to remove all elements from arr2 that have a type contained in arr1:

    arr1 = ['A', 'B', 'C']

    arr2 = [
        [
        'name' => 'jane',
        'type' => 'X'
        ],
        [
        'name' => 'jon',
        'type' => 'B'
        ]
    ]

So jon should be removed. Is there some built in function like array_diff?

Chris
  • 13,100
  • 23
  • 79
  • 162
  • No, use `foreach+unset` or `array_filter` with a callback. – u_mulder Nov 15 '17 at 19:46
  • We are always glad to help and support new coders but ***you need to help yourself first. :-)*** After [**doing more research**](https://meta.stackoverflow.com/q/261592/1011527) if you have a problem **post what you've tried** with a **clear explanation of what isn't working** and provide [a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). Read [How to Ask](http://stackoverflow.com/help/how-to-ask) a good question. Be sure to [take the tour](http://stackoverflow.com/tour) and read [this](https://meta.stackoverflow.com/q/347937/1011527). – Jay Blanchard Nov 15 '17 at 19:59

4 Answers4

4

One of solutions using array_filter:

print_r(array_filter(
    $arr2, 
    function($v) use($arr1) { return !in_array($v['type'], $arr1); }
));
u_mulder
  • 54,101
  • 5
  • 48
  • 64
1

Here's another if the type is unique:

$result = array_diff_key(array_column($arr2, null, 'type'), array_flip($arr1));
  • extract an array from $arr2 keyed (indexed) by the type column
  • flip $arr1 to get values as keys
  • get the key differences

Run array_values on it to re-index if needed.

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
0

I don't think there's a way to do it with just one built-in array function, but you can combine some of them to do it.

$record_types = array_column($arr2, 'type');

$records_to_keep = array_diff($record_types, $arr1);

$result = array_intersect_key($arr2, $records_to_keep);
Don't Panic
  • 41,125
  • 10
  • 61
  • 80
0

Foreach the 2nd array and check if the type is in arr1. If so then simply delete(unset) it.

foreach(array_keys(arr2) as $Key) {
   if (in_array(arr2[$Key]['type'],arr1)) { unset(arr2[$Key]); }
}
Pain67
  • 326
  • 1
  • 9