There are 3 operations with sets in mathematics: intersection, difference and union (unification). In PHP we can do this operations with arrays:
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'];
See array_merge
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']
+
operatorSee + operator
$a + $b; // [0 => 'a', 1 => 'b']
$b + $a; // [0 => 'b', 1 => 'c']
array_merge
array_merge($c, $d); // ['a' => 'AA', 'b' => 'B', 'c' => 'C']
array_merge($d, $c); // ['a' => 'A', 'c' => 'C', 'b' => 'B']
+
operator$c + $d; // ['a' => 'A', 'b' => 'B', 'c' => 'C']
$d + $c; // ['a' => 'AA', 'c' => 'C', 'b' => 'B']
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
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" }
Just use $array1 + $array2
It will result union of both array.