Tutorialspoint.dev

PHP | Find Intersection of two arrays

You are given two arrays of n-elements each. You have to find all the common elements of both elements, without using any loop in php and print the resulting array of common elements.

Example:

Input : array1[] = {3, 5, 2, 7, 9}, 
        array2[] = {4, 3, 2, 7, 8}
Output : array (
                [0] => 3,
                [1] => 2,
                [2] => 7)
                
Input : array1[] = {3, 5, 7}, 
        array2[] = {2, 4, 6}
Output : array (
                )

In C/Java, we have to traverse one of the array and for each element you have to check its presence in second array. But PHP provides an inbuilt function (array_intersect()) which returns the common elements (intersect) of two array.

array_intersect($array1, $array2) : Returns an array containing all the values of array1 that are present in array2.
Note that keys are preserved.

Note : As array_intersect() returns array with preserved keys, we will use array_values() which will re-order the keys.

// find intersect of both array
$result = array_intersect($array1, $array2);

// re-order keys
$result = array_values($result);

// print resultant array
print_r($result);
<?php
// declare arrays
$array1 = array(2, 5, 7, 6, 9);
$array2 = array(3, 2, 5, 6, 8);
  
// find intersect of both array
$result = array_intersect($array1, $array2);
  
// re-order keys
$result = array_values($result);
  
// print resultant array
print_r($result);
?>

Output:

Array
(
    [0] => 2
    [1] => 5
    [2] => 6
)


This article is attributed to GeeksforGeeks.org

You Might Also Like

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter