What is the array_intersect() function in PHP?

Overview

The array_intersect() function will check for an intersection point among several arrays. The function accepts any amount of arrays and computes the intersection among them. This intersects either a single value or more and will be returned in an array. If no intersect is found, the array will be returned as empty. PHP version 4.0.1 and later versions support this function.

The intersect computed by the array_intersect() function is the element(s) that can be found in all of the array parameters passed to it.

Syntax

array_intersect($arrayVal1, ....$arrayValn)
  • $arrayVal1, ....$arrayValn : These indicate that the arrays passed are a minimum of two and a maximum of any amount of arrays. So we can pass as many arrays as we can. These arrays will all be searched through, in order to find value(s) that cut across them all.

Return value

The function returns an array containing the computed intersection value(s). It returns an empty array if no intersection exists.

Code

In the code widget below, we will compute the intersection between values in arrays.

<?php
//declare the arrays to be used
$firstArray1 = array("cam" => "read", "study", "plate");
$otherArray1 = array("bam" => "pots", "house", "read");
$otherArray2 = array("jam" => "study", "pizza", "peanut", "read");
//checks for the only common value in all three arrays.
$output = array_intersect($firstArray1, $otherArray1, $otherArray2);
print_r($output);
//declare another set of arrays with nothing common amongst the 3
$firstArray2 = array("cam", "study", "plate");
$otherArray3 = array("bam" => "pots", "house", "read");
$otherArray4 = array("jam" => "study", "pizza", "peanut", "read");
//all arrays has nothing in common so empty array is returned
$outcome = array_intersect($firstArray2, $otherArray3, $otherArray4);
print_r($outcome);
?>

Explanation

  • Lines 4–6: We declare a few array values.
  • Line 9 : The array_intersect() function will check for the only common value(s) in all three arrays and return such value(s) in an array.
  • Line 10: We display the returned value.
  • Lines 13–15: We declare another set with nothing common amongst any of them.
  • Line 18: We use the array_intersect() method used here to return an empty array. That is because there is no intersection between the three arrays.
  • Line 19: We display the return value from the operation on line 18.