PHP array_intersect() Function

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

  1. array1(required): The array to compare from.
  2. array2(required): The array to compare against the first array.
  3. 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 RepresentationVisual Representation of PHP array_intersect() Function

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 ArraysVisual Representation of 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.

1 thought on “PHP array_intersect() Function”

  1. 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 )

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.