PHP | array_intersect_key() Function

This builtin function of PHP is used to compute the intersection of two or more arrays. The function is different from array_intersect() and array_intersect_assoc() in a way that it uses the keys for the comparison and returns the matching key elements. The function prints only those elements of the first array whose keys matches with the elements of all other arrays.
You may refer to array_intersect() and array_intersect_assoc() for better understanding.

Syntax:

array array_intersect_key($array1, $array2, $array3, $array4...)

Parameters: The array_intersect_key() function takes at least two arrays as arguments. It can take any number of arrays greater than or equal to two separated by commas (‘,’).



Return Type: The function returns another array containing the elements of the first array that are present in all other arrays passed as the parameter whose key matches with each other. If no keys matches then, a NULL array is returned.

Examples:

Input : $array1 = ("1" => "aakash", "2" => "rishav", "3" => "gaurav")
        $array2 = ("1" => "shyam", "2" => "rishi", "5" => "rishav")
        $array3 = ("1" => "aakash", "4" => "raghav", "2" => "ravi")
Output :
        Array
        (
          [1] => aakash
          [2] => rishav
        )

Below program illustrate the array_intersect_key() function. In the below program, we have used array_intersect_key() to find the intersection between arrays. Let’s look closer at the outputs of this and other functions of array_intersect() and array_intersect_assoc() to know the difference.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
   
// PHP program to illustrate the use 
// of array_intersect_key() function
  
$array1 = array("1" => "aakash", "2" => "rishav", "3" => "gaurav");
$array2 = array("1" => "shyam", "2" => "rishi", "5" => "rishav");
$array3 = array("1" => "aakash", "4" => "raghav", "2" => "ravi");
  
print_r(array_intersect_key($array1, $array2, $array3));
   
?>

chevron_right


Output:

Array
(
    [1] => aakash
    [2] => rishav
)

Reference:
http://php.net/manual/en/function.array-intersect-key.php



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.