PHP merge arrays with only NOT DUPLICATED values

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.

Tags:

Php

Arrays

Merge