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.
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.The function returns an array containing the computed intersection value(s). It returns an empty array if no intersection exists.
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);?>
array_intersect()
function will check for the only common value(s) in all three arrays and return such value(s) in an array.array_intersect()
method used here to return an empty array. That is because there is no intersection between the three arrays.