Search code examples
phparraysmergeunique

Merge two arrays containing objects and remove duplicate values


I need to merge two arrays of objects into 1 array and remove duplicate email values.

How can I do that?

These are my sample arrays:

$array1 = [
    (object) ["email" => "gffggfg"],
    (object) ["email" => "[email protected]"],
    (object) ["email" => "wefewf"],
];
$array2 = [
    (object) ["email" => "[email protected]"],
    (object) ["email" => "wefwef"],
    (object) ["email" => "wefewf"],
];

My expected result is:

[
   (object) ['email' => 'gffggfg'],
   (object) ['email' => '[email protected]'],
   (object) ['email' => 'wefewf'],
   (object) ['email' => '[email protected]'],
   (object) ['email' => 'wefwef'],
]

Solution

  • You can combine the array_merge() function with the array_unique() function (both titles are pretty self-explanatory)

    $array = array_unique (array_merge ($array1, $array2));