PHP array_intersect

Last modified on February 24th, 2017 by Vincy.

PHP array_intersect() function is used to find intersection between arrays. This function can accept multiple arguments to compare. After comparison, this function returns an 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.




PHP array_intersect Example

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

$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 "</PRE>";

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

    [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 an algorithm for the intersection.

Download PHP array_intersect Source Code

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top