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

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

Leave a Comment