 chap3_0672323257

• Print

3.12 Determining the Union, Intersection, or Difference Between Two Arrays

You want to find out the unions and differences of two arrays.

Technique

To find the intersection of two arrays, use the array_intersect() function:

```<?php
// Define the Arrays

\$intersection = array_intersect (\$common, \$oscar_wilde);
?>```

Or, if you want to know how many different items and how many similarities exist:

```<?php
// Define the Arrays

\$difference  = array_diff (\$common, \$oscar_wilde);
\$intersection = array_intersect (\$common, \$oscar_wilde);

\$diff_num   = count (\$difference);
\$intersect_num = count (\$intersection);
?>```

If you want to calculate the union of two arrays, keep an index of what you've already seen in one array and then match it with the next array:

```<?php
\$common   = array("Marriages", "were", "made", "in", "heaven");
\$oscar_wilde = array("Divorces", "were", "made", "in", "heaven");

\$union = array();

foreach (\$common as \$ele) { \$seen[\$ele] = 1; }

foreach (\$oscar_wilde as \$ele) {
if (\$seen[\$ele] == 1) {
array_push (\$union, \$ele);
\$seen[\$ele]++;
}
}
?> ```

Finally, let us calculate the symmetric difference of the two arrays:

```<?php
// Define the Arrays

\$symdiff = array();

foreach (\$common as \$ele) {
if (!in_array (\$oscar_wilde, \$ele)) {
array_push (\$symdiff, \$ele);
}
}

foreach (\$oscar_wilde as \$ele) {
if (!in_array (\$common, \$ele)) {
array_push (\$symdiff, \$ele);
}
}

\$symdiff = array_unique(\$symdiff);
?>```