PHP Find Union & Intersection of Two Unsorted Arrays
Last Updated :
20 Mar, 2024
Given two unsorted arrays, i.e. arr1, and arr2, the task is to find the union and intersection of two unsorted arrays in PHP. Union and intersection of two arrays are common operations in data manipulation and analysis. The union of two arrays includes all the unique elements from both arrays, while the intersection includes only the elements that are present in both arrays.
Below are the approaches to find the union and intersection of two unsorted array using PHP:
Using Built-in Functions
PHP provides built-in functions array_merge() and array_intersect() which can be used to find the union and intersection of arrays, respectively.
- array_merge($arr1, $arr2) merges the two arrays into one.
- array_unique($arr1) removes duplicate values from the array to form the union.
- array_intersect($arr1, $arr2) finds the intersection of the two arrays.
Example: The below mentioned code calculates the Union & Intersection of two unsorted array in PHP using above mentioned approach.
PHP
<?php
// Define two unsorted arrays
$arr1 = [3, 5, 8, 10];
$arr2 = [5, 10, 15, 20];
// Find the union of the arrays
$union = array_unique(array_merge($arr1, $arr2));
// Find the intersection of the arrays
$intersection = array_intersect($arr1, $arr2);
echo "Union: ";
print_r($union);
echo "\nIntersection: ";
print_r($intersection);
?>
OutputUnion: Array
(
[0] => 3
[1] => 5
[2] => 8
[3] => 10
[6] => 15
[7] => 20
)
Intersection: Array
(
[1] => 5
[3] => 10
)
Using Loops and Conditional Statements
You can also find the union and intersection of two arrays manually using loops and conditional statements.
- First we adds all elements of $arr1 to the $union array.
- Then, for each element of $arr2:
- If the element is not already in $union, it is added to form the union.
- If the element is also in $arr1, it is added to $intersection to form the intersection.
Example: The below mentioned code calculates the Union & Intersection of two unsorted array in PHP using above mentioned approach.
PHP
<?php
// Define two unsorted arrays
$arr1 = [3, 5, 8, 10];
$arr2 = [5, 10, 15, 20];
// Initialize empty arrays for
// union and intersection
$union = [];
$intersection = [];
// Add all elements of the first
// array to the union
foreach ($arr1 as $element) {
$union[] = $element;
}
// Iterate through the second array
foreach ($arr2 as $element) {
// Add to the union if not already present
if (!in_array($element, $union)) {
$union[] = $element;
}
// Add to the intersection if present
// in the first array
if (in_array($element, $arr1)) {
$intersection[] = $element;
}
}
// Display the results
echo "Union: ";
print_r($union);
echo "\nIntersection: ";
print_r($intersection);
?>
OutputUnion: Array
(
[0] => 3
[1] => 5
[2] => 8
[3] => 10
[4] => 15
[5] => 20
)
Intersection: Array
(
[0] => 5
[1] => 10
)
Share your thoughts in the comments
Please Login to comment...