0

I have 2 arrays -

Array
(
    [0] => Array
        (
            [description] => 5390BF675E1464F32202B
            [to_email] => test@test.com
        )

    [1] => Array
        (
            [description] => 5390BF675E1464F32202B
            [to_email] => test3@test.com
        )

    [2] => Array
        (
            [description] => 5390BF675E1464F32202B
            [to_email] => testagain@gmail.com
        )

)

Array
(
    [0] => Array
        (
            [to_email] => test@test.com
        )

    [1] => Array
        (
            [to_email] => test3@test.com
        )

)

I want to get the values from Array 1 which are different from the second array.

I have tried using -

$result = array_diff_assoc($array1, $array2);

AND

$result = array_diff($array1, $array2);

But both gave error like -

Notice: Array to string conversion in

Outcome that I am expecting is

Array
(
 [0] => Array
        (
            [description] => 5390BF675E1464F32202B
            [to_email] => testagain@gmail.com
        )
 )
Nick
  • 138,499
  • 22
  • 57
  • 95
Gagan
  • 294
  • 3
  • 16

1 Answers1

2

You can generate a list of the email addresses to exclude using array_column. We use the 3 parameter form to index that array by the email addresses as it makes it easier to filter with:

$exclude_ids = array_column($array2, 'to_email', 'to_email');

We can then use array_filter to filter $array1:

$output = array_filter($array1, function ($v) use ($exclude_ids) {
    return !isset($exclude_ids[$v['to_email']]);
});
print_r($output);

Output:

Array
(
    [2] => Array
        (
            [description] => 5390BF675E1464F32202B
            [to_email] => testagain@gmail.com
        )    
)

Demo on 3v4l.org

Note if you want the output array re-indexed to 0, just use

$output = array_values($output);
Nick
  • 138,499
  • 22
  • 57
  • 95
  • Thanks, it seems like working Just couple of things- 1) I will have multiple count in $array and $array2 in future will it still work, and if the values are same? 2) Can we set the index to 0 instead of 2? – Gagan Jan 15 '20 at 05:55
  • 1
    @Gagan what do you mean by "multiple count"? in terms of re-indexing see the last part of the answer. – Nick Jan 15 '20 at 05:56
  • All I meant was i this example the $array1 is having 3 values and $array2 have 2 in future there will be 20's of values in both arrays, so the solution will be dynamic. However, I think it should work. But just confirming – Gagan Jan 15 '20 at 05:58
  • 1
    @Gagan yes, it will work regardless of how many values are in either array. – Nick Jan 15 '20 at 05:59