### Relations Between Sets (Mathematics) and Arrays (Programming)

The topic of “Sets” we study in Mathematics has widespread applications in Computer Science. This is especially true with computer programming.

An array in computer programming is a data structure that has list of items with indexes. Whereas a Set in Mathematics is a list of well defined collection of unique items.

An array is basically a set with indexes.

**Similarities:**

- Both are data structures
- Both hold a list of items
- Both have operations that can be performed, such as union, intersection etc

**Differences:**

Sets:

- It does not allow duplicate items
- It does not have index for the items it contains
- A specific item cannot be taken and has to be traversed one by one until it is found or not found

Arrays:

- It allows duplicate items
- It has index for each item it contains
- A specific item can be taken using its given index

Moreover, to show the similarity of operations performed in sets and arrays, I’ll use example of PHP arrays and provided functions.

Let’s say we have three arrays $u, $a and $b. $u being the universal array containing both $a and $b.

$u = [1,2,3,4,5,6,7,8,9];$a = [1,2,3];$b = [1,2,3,4,5];

**1.Union**

The union of $a and $b can be taken as follows:

$a_union_b = $a + $b;

echo 'a_union_b = [' . implode(',', $a_union_b) . '] <br>';

If we run the code we get:

a_union_b = [1,2,3,4,5]

**2. Intersection**

Similarly, intersection of $a and $b:

$a_intersection_b = array_intersect($a, $b);

echo 'a_intersection_b = [' . implode(',', $a_intersection_b) . '] <br>';

Will give us the following output:

a_intersection_b = [1,2,3]

**3. Difference (A-B)**

$a_diff_b = array_diff($a, $b);

echo 'a_diff_b = [' . implode(',', $a_diff_b) . '] <br>';

Gives the output:

a_diff_b = []

**4. Difference (B-A)**

$b_diff_a = array_diff($b, $a);

echo 'b_diff_a = [' . implode(',', $b_diff_a) . '] <br>';

Gives the output:

b_diff_a = [4,5]

**5. A Complement**

$a_complement = array_diff($u, $a);

echo 'a_complement = [' . implode(',', $a_complement) . '] <br>';

Gives the output:

a_complement = [4,5,6,7,8,9]

6. A delta B

$a_delta_b = $a_diff_b + $b_diff_a;

echo 'a_delta_b = [' . implode(',', $a_delta_b) . '] <br>';

Gives the output:

a_delta_b = [4,5]

Thus, we can see that they are similar in many ways, and have some differences too.

Thanks for reading the article, hope you enjoyed it. Don’t forget to give claps and share it if you found it helpful :)

Other series you may be interested in:

Relation between Sets (Mathematics) and Arrays (Programming) was originally published in Hacker Noon on Medium, where people are continuing the conversation by highlighting and responding to this story.