PHP array_intersect() function is “used to compute the intersection of two or more arrays.” This function returns a new array containing all the values from the first array that also exist in all the other arrays.
Keep in mind that keys are preserved.
Syntax
array_intersect(array1,array2,array3...);
Parameters
- array1(required): The array to compare from.
- array2(required): The array to compare against the first array.
- array3(optional): More arrays to compare against the first array.
In PHP 8.0.0, this function can be called with only one parameter.
Return value
It returns an array containing the first array’s elements that are present in all of the other arrays. If no elements match, then an empty array is returned.
Visual Representation
Example 1: How to Use array_intersect() Function
<?php
$arrA = [
'a' => 'AppDividend',
'b' => 'Hermès',
'c' => 'Gucci'];
$arrB = [
'd' => 'AppDividend',
'e' => 'Gucci',
'f' => 'Google'];
$result=array_intersect($arrA,$arrB);
print_r($result);
Output
Array
(
[a] => AppDividend
[c] => Gucci
)
In this example, the strings “AppDividend” and “Gucci” are present in both $arrA and $arrB, so they are included in the $result array. The keys for these values from the first array are preserved in the result.
Example 2: Three Arrays
<?php
$arrA = [
'a' => 'AppDividend',
'b' => 'Hermès',
'c' => 'Gucci'];
$arrB = [
'd' => 'AppDividend',
'e' => 'Gucci',
'f' => 'Google'];
$arrC = [
'y' => 'Yahoo',
'z' => 'AppDividend'];
$result=array_intersect($arrA,$arrB,$arrC);
print_r($result);
Output
Array
(
[a] => AppDividend
)
Example 3: Handle duplicate array values
The array_intersect() function handles the duplicate items in the arrays differently. If there are duplicate values in the first array, all the matching duplicate values will be returned.
<?php
$arrA = [21, 19, 21, 46];
$arrB = [19, 21, 29];
$result = array_intersect($arrA, $arrB);
print_r($result);
Output
Array
(
[0] => 21
[1] => 19
[2] => 21
)
That’s it.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.
how to get same value
Array ( [0] => 13 [1] => 14 [2] => 15 [3] => 16 [4] => 17 [5] => 18 )
Array ( [0] => 9 [1] => 10 [2] => 16 [3] => 17 )