September 2, 2022

What effective way to filter one multidimensional array by another?

Let we have 2 multidimensional arrays:

$arr1 = [
    ["URL" => "/1/1/1", "cnt" => "1"],
    ["URL" => "/2/2/2", "cnt" => "1"],
    ["URL" => "/3/3/3", "cnt" => "1"]
];

$arr2 = [
    ["URL" => "/2/2/2", "cnt" => "1"],
    ["URL" => "/4/4/4", "cnt" => "1"]
];

The problem is filer out all records from first array where exists records with same value of "URL" field

Of course we can to use nested loops for this, but this is not best way

The most effective solution is build map of all values of URL from second array and after use array_filter function:

$url2arr = array_column($arr2, 'url', 'url');

$res = array_filter($arr1, fn($el)=>!isset($url2arr[$el['url']]));

print_r($res);

php code online