array_uintersect()
is the first thing that comes to mind -- it allows you to compare the intersecting values between two arrays. The fact that you have arrays of different depths means that you will need a custom callback. Within that callback, you cannot be sure that $a1
values will be represented in temporary variable $a
, nor sure that $a2
values will be represented in $b
. To properly handle each iteration, check for an age
key else fall back to the base variable).
Code: (Demo)
$a1 = [
['name' => 'mike', 'age' => 18],
['name' => 'james', 'age' => 22],
['name' => 'sarah', 'age' => 35],
['name' => 'ken', 'age' => 29],
];
$a2 = [22, 25, 35, 40];
var_export(
array_uintersect(
$a1,
$a2,
fn($a, $b) => ($a['age'] ?? $a) <=> ($b['age'] ?? $b)
)
);
Alternatively, a more concise approach involves making iterated calls of in_array()
inside of an array_filter()
call. Generally, I strongly advise against making iterated calls of in_array()
because in_array()
is one of the slowest ways to make checks on array values. Depending on the actual size of the two input arrays, the following snippet may perform better or worse than array_uintersect()
-- I did not do any benchmarks.
Code: (Demo)
var_export(
array_filter($a1, fn($row) => in_array($row['age'], $a2))
);