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);
filter_none

edit
close

play_arrow

link
brightness_4
code

<?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);
?>

chevron_right


Output:

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


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.