PHP merge arrays with only NOT DUPLICATED values

I need to merge two arrays into 1 array but what I need is to remove before the main data they b oth have in common (duplicated values i mean), I need only unique values when merged.

How can i do that?

This is the array example:

First array

array(3) { 
    [0]=> object(stdClass)#17 (1) { 
        ["email"]=> string(7) "gffggfg" 
    } 
    [1]=> object(stdClass)#18 (1) { 
        ["email"]=> string(6) "[email protected]" 
    } 
    [2]=> object(stdClass)#19 (1) { 
        ["email"]=> string(6) "wefewf" 
    } 
} 

Second array

array(3) { 
    [0]=> object(stdClass)#17 (1) { 
        ["email"]=> string(7) "[email protected]" 
    } 
    [1]=> object(stdClass)#18 (1) { 
        ["email"]=> string(6) "wefwef" 
    } 
    [2]=> object(stdClass)#19 (1) { 
        ["email"]=> string(6) "wefewf" 
    } 
} 

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));

If I understand the question correctly:

 $a1 = Array(1,2,3,4);
 $a2 = Array(4,5,6,7);
 $array =  array_diff(array_merge($a1,$a2),array_intersect($a1,$a2));
 print_r($array);

return

Array
(
[0] => 1
[1] => 2
[2] => 3
[5] => 5
[6] => 6
[7] => 7
)

I've been running some benchmarks of all the ways I can imagine of doing this. I ran tests on stacking lots of arrays of 10-20 string elements, resulting in one array with all unique strings in there. This sould be about the same for stacking just 2 arrays.

The fastest I've found was the simplest thing I tried.

$uniques = [];
foreach($manyArrays as $arr ) {
  $uniques = array_unique(array_merge($uniques, $arr));
}

I had branded this 'too naive to work', since it has to sort the uniques array every iteration. However this faster than any other method. Testing with 500.000 elements in manyArrays, each containing 10-20 strings om PHP 7.3.

A close second is this method, which is about 10% slower.

$uniques = [];
foreach($manyArrays as $arr ) {
  foreach($arr as $v) {
    if( !in_array($v, $uniques, false) ) {
      $uniques[] = $v;
    }
  }
}

The second method could be better in some cases, as this supports the 'strict' parameter of in_array() for strict type checking. Tho if set to true, the second option does become significantly slower than the first (around 40%). The first option does not support strict type checking.


Faster solution:

function concatArrays($arrays){
    $buf = [];
    foreach($arrays as $arr){
        foreach($arr as $v){
            $buf[$v] = true;
        }
    }
    return array_keys($buf);
}


$array = concatArrays([$array1, $array2]);