Dmytro Zarezenko Dmytro Zarezenko - 5 days ago 6
PHP Question

Set Theory Union of arrays in PHP

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

Answer

Try array_merge:

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

PHP Manual

Comments