37

There are 3 operations with sets in mathematics: intersection, difference and union (unification). In PHP we can do this operations with arrays:

  • intersection: array_intersect
  • difference: array_diff

What function is for union?

No duplicates can be in the result array (like array_intersect and array_diff).

If indexes are numeric then array_merge will not overwrite the original value, but will be appended (PHP docs).

icc97
  • 11,395
  • 8
  • 76
  • 90
Dmytro Zarezenko
  • 10,526
  • 11
  • 62
  • 104

11 Answers11

56

Try array_merge:

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

PHP Manual

adrien
  • 4,399
  • 26
  • 26
  • 2
    I don't understand why this is accepted and upvoted more than the answers pointing out the union operator (+). Am I missing something about the union operator? – mwotton Nov 27 '13 at 03:50
  • 8
    PHP's "union operator" does not perform a mathematical union. var_dump([1,2]+[3,4]) has the mathematical union of [1,2,3,4] (due to 4 values), but the two arrays only have two unique keys, therefore the script will output [1,2]. PHP's "union" operator is totally unrelated to a mathematical union – Josh Ribakoff Mar 24 '14 at 22:44
  • 1
    Note that array_unique won't reindex the keys for numeric arrays - you may need to use `array_values` as well if the array indexes need to be sequential. – Brilliand Apr 01 '14 at 19:06
  • 2
    @JoshRibakoff PHP's union operator is a mathematical union of the array's keys, not its values. It is certainly not "totally unrelated" to a mathematical union. You can use `array_flip` to put the values in the keys so the array union operator applies - see my answer. – Brilliand Mar 25 '15 at 17:08
  • 2
    Beware that this will not work if the input arrays contain string keys. For example: `php -r 'var_dump(array_unique(array_merge(["a"=>"cat","b"=>"dog"], ["b"=>"cow","c"=>"hen"])));'` produces ['cat','cow','hen'] because values with the same string key are overwritten. To avoid this problem, call array_values on each input array before merging, as follows: `php -r 'var_dump(array_unique(array_merge(array_values(["a"=>"cat","b"=>"dog"]), array_values(["b"=>"cow","c"=>"hen"]))));'` – humbads Sep 04 '15 at 01:35
  • The matches the top comment from the PHP: Array Operators documentation: http://php.net/manual/en/language.operators.array.php#86379, which is taken from the "Programming PHP" O'Reilly book by Rasmus Ledorf. – icc97 Nov 27 '16 at 10:49
  • Warning: a php array is not a mathematical set, it only makes sense to talk about a union OF KEYS or a union OF VALUES in the context of php, the full set of (key,val) pairs is not necessarily preserved by a merge [but, and this is tricky, it will be if all the keys in both arrays are unique]. – tjb Jan 23 '19 at 05:57
11

array_unique( array_merge( ... ) )

Brian
  • 15,599
  • 4
  • 46
  • 63
11

Adrien's answer won't necessary produce a sequentially numbered array from two sequentially numbered arrays - here are some options that will:

array_values(array_unique(array_merge($array1, $array2)));

(Adrien's answer with renumbering the keys afterward)

array_keys(array_flip($array1)+array_flip($array2))

(Put the values in the keys, and use the array union operator)

array_merge($array1, array_diff($array2, $array1))

(Remove the shared values from the second array before merging)

Benchmark results (for merging two arrays of length 1000 a thousand times on my system):

  • Unique (Adrien's version): 2.862163066864 seconds
  • Values_Unique: 3.12 seconds
  • Keys_Flip: 2.34 seconds
  • Merge_Diff: 2.64 seconds

Same test, but with the two arrays being very similar (at least 80% duplicate):

  • Unique (Adrien's version): 2.92 seconds
  • Values_Unique: 3.15 seconds
  • Keys_Flip: 1.84 seconds
  • Merge_Diff: 2.36 seconds

It seems using the array union operator to do the actual union is the fastest method. Note however that array_flip is only safe if the array's values are all strings or all integers; if you have to produce the union of an array of objects, I recommend the version with array_merge and array_diff.

Brilliand
  • 13,404
  • 6
  • 46
  • 58
6

use "+" operator to do so. See the link Array Operators

RJ Anoop
  • 763
  • 13
  • 26
  • @GordonM It's awkward because the `+` operator is defined as being the array union. You're right that it does a union of keys, but it [chooses the first array over the second when removing duplicates](https://softonsofa.com/php-array_merge-vs-array_replace-vs-plus-aka-union/) which is the opposite of `array_merge`. – icc97 Nov 27 '16 at 10:05
  • Actually this answer is just a duplicate of http://stackoverflow.com/a/10485300/327074 and http://stackoverflow.com/a/10485348/327074 – icc97 Nov 27 '16 at 10:08
5

Use array_unique and array_merge together.

Oscar Jara
  • 14,129
  • 10
  • 62
  • 94
4

From the code in the PHP: Array Operators documentation:

<?php
$a = array("a" => "apple", "b" => "banana");
$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");

$c = $a + $b; // Union of $a and $b
echo "Union of \$a and \$b: \n";
var_dump($c);

$c = $b + $a; // Union of $b and $a
echo "Union of \$b and \$a: \n";
var_dump($c);
?>

When executed, this script will print the following:

Union of $a and $b:
array(3) {
  ["a"]=>
  string(5) "apple"
  ["b"]=>
  string(6) "banana"
  ["c"]=>
  string(6) "cherry"
}
Union of $b and $a:
array(3) {
  ["a"]=>
  string(4) "pear"
  ["b"]=>
  string(10) "strawberry"
  ["c"]=>
  string(6) "cherry"
}
icc97
  • 11,395
  • 8
  • 76
  • 90
Marian Zburlea
  • 9,177
  • 4
  • 31
  • 37
  • From the [top comment](http://php.net/manual/en/language.operators.array.php#86379) on the [PHP: Array Operators](http://php.net/manual/en/language.operators.array.php) documentation. *"The union operator did not behave as I thought it would on first glance. It implements a union (of sorts) based on the keys of the array, not on the values."* He then goes on to suggest `array_unique(array_merge($a,$b))` – icc97 Nov 27 '16 at 10:20
  • I've added the link, but if you are going to copy and paste directly from the PHP source code you should add in a reference. – icc97 Nov 27 '16 at 10:45
2

The OP did not specify whether the union is by value or by key and PHP has array_merge for merging values and + for merging the keys. The results depends on whether the array is indexed or keyed and which array comes first.

$a = ['a', 'b'];
$b = ['b', 'c'];

$c = ['a' => 'A',  'b' => 'B'];
‌‌$d = ['a' => 'AA', 'c' => 'C'];

Indexed array

See array_merge

By value using array_merge

‌‌array_merge($a, $b); // [‌0 => 'a', 1 => 'b', 2 => 'b', 3 => 'c']
‌‌array_merge($b, $a); // ‌[0 => 'b', 1 => 'c', 2 => 'a', 3 => 'b']

merge by key using + operator

See + operator

‌‌$a + $b; ‌// [0 => 'a', 1 => 'b']
$b + $a; // [0 => 'b', 1 => 'c']

Keyed array

By value using array_merge

‌array_merge($c, $d); // ‌['a' => 'AA', 'b' => 'B', 'c' => 'C']
array_merge($d, $c); // ['a' => 'A',  'c' => 'C', 'b' => 'B']

merge by key using + operator

$c + $d; // [‌'a' => 'A',  'b' => 'B', 'c' => 'C']
‌‌$d + $c; // ‌['a' => 'AA', 'c' => 'C', 'b' => 'B']
Clemens Tolboom
  • 1,872
  • 18
  • 30
1
$result = array_merge_recursive($first, $second);

can be useful when you have arrays with arrays inside.

ackuser
  • 5,681
  • 5
  • 40
  • 48
0

The + operator:

$x[0] = 4;
$x[1] = 1;

$y[0] = 9;
$y[2] = 5;

$u = $y + $x;

// Results in:
$u[0] === 9;
$u[1] === 1;
$u[2] === 5;

Note that $x + $y != $y + $x

Paul
  • 139,544
  • 27
  • 275
  • 264
0

Just use $array1 + $array2 It will result union of both array.

Altaf Hussain
  • 1,048
  • 2
  • 12
  • 25
0

Try this:

function array_union($array1, $array2){
    return array_unique(array_merge($array1, $array2));
}
Raja Bilal
  • 87
  • 1
  • 12