Search code examples
phparraysforeachintersect

Check if any value in any 2 arrays with different dimension is same in php


I have 2 arrays -

$arr1 =

Array
(
    [0] => Array
        (
            [id] => 1
            [sender_email] => [email protected]
            [to_email] => [email protected]
            [description] => 5390BF675E1464F32202B
            [created_at] => 2020-01-21 04:50:21
            [status] => 1
        )

    [1] => Array
        (
            [id] => 30
            [sender_email] => [email protected]
            [to_email] => [email protected]
            [description] => 729237A55E2EDCB80B18F
            [created_at] => 2020-01-27 12:51:34
            [status] => 1
        )
[2] => Array
        (
            [id] => 31
            [sender_email] => [email protected]
            [to_email] => [email protected]
            [description] => 729237A55E2EDCB80B18F
            [created_at] => 2020-01-27 12:51:34
            [status] => 1
        )

)

$arr2 =
Array
(
    [0] => [email protected]
    [1] =>  [email protected]
    [2] =>  [email protected]
)

I am trying to find the matching values from $arr2 which also exist in $arr1.

I tried with

if(array_intersect($arr2, $arr1)) {
            die('wrong');
        }

But it show error like -

 Notice: Array to string conversion in

I think due to difference in structure. How can this be achieved? It will be really helpful if I can get all matching values in one array. The column name will always be same but I request to not make that an inclusion in the code.


Solution

  • This should work:

    $matches = []; // array which will contains matches
    foreach($arr1 as &$el){ // loop through the elements
       if(array_intersect($arr2,$el)) array_push($matches, $el); //and if there is at least one elements as intersect of the two arrays, add it
    }