Search code examples
phparraysmultidimensional-arrayfilterarray-filter

Keep rows of a 2d array if their column value is found in a flat whitelist array


I want to filter a 2d array to keep rows where the mykey column value is found in a whitelist of values.

[
  ['mykey' => 40],
  ['mykey' => 37],
  ['mykey' => 14],
  ['mykey' => 7],
]

I know how to filter by one value using array_filter().

$r = array_filter($res, function($e){
         return $e['mykey'] == 37;
     });

However, I need to compare an array of numbers something like this:

$r = array_filter($res, function($e){
         return $e['mykey'] == [37, 14, 7];
     });

How can I filter the array so that if mykey is equal to any of those values, then the whole row should be retained?


Solution

  • You can use in_array to check if the value exists in a list.

    <?php
    ...
    
    $r = array_filter($res, function($e){
        return in_array($e['mykey'], [37, 14, 7]);
    });