PHP array_intersect

PHP array_intersect() function is used to find intersection between arrays. This function can accept multiple arguments to compare. After comparison, this function returns array of intersecting elements that are commonly available in all the given input arrays.

array_intersect() is the reverse of PHP array_diff() which returns the elements that are not in the arguments.

intersection

Syntax:

array_intersect($input_array1,$input_array2,$input_array3...)

PHP array_intersect Example

In this example, we are going to pass four arrays as parameters.

<?php
$soft_toys = array("Baby Pillow", "Teddy Bear", "Chicklings");
$baby_toys = array("Toy phone", "Baby Pillow", "Lighting Ball", "Teddy Bear");
$gift_items = array("Coloring Fun", "Baby Pillow", "Barbies", "Teddy Bear");
$kids_bedroom_set = array("Teddy Bear", "Baby Pillow", "Night Lamp","Kids Bed");
$arrayIntersect = array_intersect($soft_toys, $baby_toys, $gift_items, $kids_bedroom_set);
print "<PRE>";
print_r($arrayIntersect);
print "</PRE>";
?>

This program prints resultant array containing values that are commonly present in all the four input arrays. The output is,

Array(
    [0] => Baby Pillow
    [1] => Teddy Bear
)

Other Array Intersection Functions in PHP

PHP includes some other functions to calculate intersected elements among input arrays. These functions are,

  • array_intersect_key() – returns intersecting elements with respect to keys.
  • array_interset_assoc() – returns intersecting elements with respect to keys and values.
  • array_intersect_ukey() – returns intersecting elements on the basis of custom functions provided algorithm for the intersection.

Download PHP array_intersect Source Code

This PHP code tutorial was published on November 25, 2013.

↑ Back to Top