[PHP] Array Union

Today I am going to discuss how to perform union operation on a group of arrays. In Set Theory, union is an operation on sets. A set is a group of unordered elements. Theoretically, every element in a set is unique, duplication is not allowed in set. Union operation is merging of multiple sets into one, by combining them together. The result will be a set.

{1,2,3,2} is not a set, because there are duplicated elements.  {1,2,3} and {3,1,2} are considered same set, because set elements are unordered.

Let set A = {1,2,3,4} and set B = {2,4,7,8,0}. Union operator is represented by a ‘∪’ symbol. Therefore the result of A ∪ B is {1,2,3,4,7,8,0}. The resultant set contains elements from both A and B. Note that there are no duplication, since the result of union is a set.

In PHP, array is not really a set because array can contain duplications, and elements are ordered. Suppose I have 2 array, how do I get a union of the 2 arrays? array_merge can merges multiple arrays together, but the resultant array may contains duplication. A ‘+’ operator can be used on arrays. PHP called it “union”. I find it misleading!

With array_unique, you can get an array of unique elements. When combined with array_merge, it becomes a real union operation.

Ref:

Posted in Tao Of Programming at May 8th, 2009. No Comments.