PHP array_intersect() function
The array_intersect () function in PHP is used to compute the intersection of arrays. It returns an array containing all the entries from array1 that are present in all the other arrays.
Syntax
array_intersect ( array $array1 , array $array2 [, array $... ])
Parameter
array1(required)- This parameter signifies the input array to compare from.
array2(required)- This parameter signifies the input array to compare against.
array3….(optional)- It represents more arrays to compare against.
Return
This function returns an array containing all the values in array1 whose values are present in all the other arrays.
Example 1
"F"); echo("\nArray 2: \n"); var_export($array2); //returning the intersection of array1 and array2 $result_array = array_intersect($array1, $array2); echo("\nIntersection: \n"); //printing the intersection of the array based on values print_r($result_array); ?>
Output
Array 1: array ( 0 => 'A', 1 => 'b', 2 => 'c', 3 => 'd', ) Array 2: array ( 0 => 'A', 1 => 'd', 2 => 'A', 5 => 'F', ) Intersection: Array ( [0] => A [3] => d )
Example 2
Output
Array 1: array ( 0 => 'aqua', 1 => 'green', 2 => 'red', 3 => 'blue', 4 => 'red', ) Array 2: array ( 0 => 'blue', 1 => 'green', 2 => 'yellow', 3 => 'blue', ) Intersection: Array ( [1] => green [3] => blue )
Example 3
"Reema", 2 => "Akash", 3 => "Sukla", 4 >"Varun",5=>"Mukta",6=>"Amar"); //initializing array2 $array2 = array(1 => "Reema", 2 => "Akash", 3 => "Tisha", 4 =>"Varun"); //initializing array3 $array3 = array(1 => "Rahul", 2 => "Akash", 3 => "Tisha", 4 =>"Varun"); //computing the intersection between array1, array2 and array3 $intersection = array_intersect($array1,$array2,$array3); //printing the intersection containing all the entries from array1 that are present in array2 nd array3 print_r($intersection); ?>
Output
Array ( [2] => Akash [4] => Varun )