How to use Built-in PHP Functions In PHP

In this method we use built-in functions provided by PHP to find the union and intersection of arrays. We use array_merge() to merge arrays and then array_unique() to remove duplicates for the union. Also we use array_intersect() to find the intersection.

Example: The below code example is a practical implementation of using built-in PHP Functions to find Union and Intersection of two unsorted arrays.

PHP
<?php
    // Function to find the union of two arrays
    function findUnion($arr1, $arr2) {
        $union = array_unique(array_merge($arr1, $arr2));
        return $union;
    }

   // Function to find the intersection of two arrays
   function findIntersection($arr1, $arr2) {
        $intersection = array_intersect($arr1, $arr2);
        return $intersection;
}

    // Example arrays
    $array1 = array(1, 2, 3, 4, 5);
    $array2 = array(4, 5, 6, 7, 8);

    // Finding union
    $unionResult = findUnion($array1, $array2);
    echo "Union: ";
    print_r($unionResult);

    // Finding intersection
    $intersectionResult = findIntersection($array1, $array2);
    echo "Intersection: ";
    print_r($intersectionResult);
?>

Output
Union: Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [7] => 6
    [8] => 7
    [9] => 8
)
Intersection: Array
(
    [3] => 4
    [4] => 5
)

  • Union:
    • Time Complexity: O(n + m)
    • Auxiliary Space: O(n + m)
  • Intersection:
    • Time Complexity: O(n * m) in the worst case
    • Auxiliary Space: O(min(n, m))

How to Find Union and Intersection of Two Unsorted Arrays in PHP?

Given two unsorted arrays representing two sets (elements in every array are distinct), find the union and intersection of two arrays in PHP.

Example: 

Input: arr1[] = {7, 1, 5, 2, 3, 6} , arr2[] = {3, 8, 6, 20, 7} 
Output: Union {1, 2, 3, 5, 6, 7, 8, 20} and Intersection as {3, 6, 7}

These are the following approaches:

Table of Content

  • Using Built-in PHP Functions
  • Using Loops and Associative Arrays
  • Using Set Data Structure (Arrays as Sets)

Similar Reads

Using Built-in PHP Functions

In this method we use built-in functions provided by PHP to find the union and intersection of arrays. We use array_merge() to merge arrays and then array_unique() to remove duplicates for the union. Also we use array_intersect() to find the intersection....

Using Loops and Associative Arrays

In this method we use loops to manually find the union and intersection. Associative arrays (or hash maps) are used to keep track of elements....

Using Set Data Structure (Arrays as Sets)

In this method we use concept of sets to find the union and intersection and Associative arrays can simulate set behavior....