Search code examples
phparraysfilterarray-filter

how can i use array_filter in php


hi i have this question

my array

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

i have an array and i wanna filter some key by a value so use this

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

but i need to campare an array of numbers something like this

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

how i can filter like this so if mykey is equal to those values so return the arrays with the values 37 14 and 7


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