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); ?> |
Array
(
[0] => 2
[1] => 5
[2] => 6
)
Recommended Posts:
- Underscore.js | _.intersection() with Examples
- How to find if two arrays contain any common item in Javascript?
- PHP | Arrays
- Associative Arrays in PHP
- Sorting Arrays in PHP 5
- Multidimensional arrays in PHP
- TypeScript Arrays
- PHP | Merging two or more arrays using array_merge()
- PHP | Check if two arrays contain same elements
- Compute the set difference using JavaScript arrays
- Merge two arrays keeping original keys in PHP
- How to find where the URL will redirected using cURL?
- PHP | Ds\Deque find() Function
- PHP | Ds\Vector find() Function
- PHP | Ds\Sequence find() Function
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.



