Search code examples
phparraysfilterarray-filterarray-intersect

Keep array rows where a column value is found in a second flat array


I have an array, $arr1 with 5 columns as such:

 key    id  name    style   age whim
 0      14  bob     big     33  no
 1      72  jill    big     22  yes
 2      39  sue     yes     111 yes
 3      994 lucy    small   23  no
 4      15  sis     med     24  no
 5      16  maj     med     87  yes
 6      879 Ike     larg    56  no
 7      286 Jed     big     23  yes

This array is in a cache, not a database.

I then have a second array with a list of id values -

$arr2 = array(0=>14, 1=>72, 2=>8790)

How do I filter $arr1 so it returns only the rows with the id values in $arr2?

I have tried to use filter function (below), array_search, and several others but cannot figure out how to make it work.

$resultingArray = [];  // create an empty array to hold rows
$filter_function = function ($row) use ($arr2) {
    foreach ($arr2 as $arr) {
        return ($row['id'] == $arr);
    }
}

Solution

  • This whole task can be accomplished with just one slick, native function call -- array_uintersect().

    Because the two compared parameters in the custom callback may come either input array, try to access from the id column and if there isn't one declared, then fallback to the parameter's value.

    Under the hood, this function performs sorting while evaluating as a means to improve execution time / processing speed. I expect this approach to outperform iterated calls of in_array() purely from a point of minimized function calls.

    Code: (Demo)

    var_export(
        array_uintersect(
            $arr1,
            $arr2,
            fn($a, $b) =>
                ($a['id'] ?? $a)
                <=>
                ($b['id'] ?? $b)
        )
    );