2

I'm trying to filter my first array by my second array. I want to filter every person whose age is 22,25,35, or 40. I have these whitelisted values store in an $a2

$a1 = [
    ['name' => 'mike',  'age' => 18],
    ['name' => 'james', 'age' => 22],
    ['name' => 'sarah', 'age' => 35],
    ['name' => 'ken',   'age' => 29],
];

$a2 = [22, 25, 35, 40];

I tried array_intersect() like:

$results = array_intersect($a2, $a1['age']);
var_dump($results);

And array_filter() but without success.

My desired output is:

[
    ['name' => 'james', 'age' => 22],
    ['name' => 'sarah', 'age' => 35]
]               
mickmackusa
  • 43,625
  • 12
  • 83
  • 136

2 Answers2

0

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))
);
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
-1

array_intersect and array_diff don't work well with multi dimensional arrays.

try this and see how work:

$a = [1,2,3,4];
$b = [2,7,8,9];
var_dump(array_intersect($a,$b)); 

the result should be [2]. if you work with multidimensional arrays and you only interesting in one column of arrays do first:

$age = array_column($a1,'age');

and then

var_dump(array_intersect($age,$a2));