PHP | array_diff_key() Function

This inbuilt function of PHP is used to get the difference between one or more arrays. This function compares the keys between one or more arrays and returns the difference between them. So, the function generally compares two arrays according to there keys and returns the elements that are present in the first array but not in other input arrays.

Note: This function is different than array_diff() and array_diff_assoc(). The first only used the values to compare. The second one uses both keys and values to compare. Where as array_diff_key() uses just the keys to compare.

Syntax:

array array_diff_key($array1, $array2, $array3, ..., $array_n)

Parameters: The function can take any number of arrays as parameters needed to be compared.

Return Type: This function compares the key of the first array of parameters with rest of the arrays and returns an array containing all the entries from $array1 that are not present in any of the other arrays.

Examples:

Input : 
$array1 = ("10"=>"RAM", "20"=>"LAXMAN", "30"=>"RAVI", 
                      "40"=>"KISHAN", "50"=>"RISHI")
$array2 = ("10"=>"RAM", "70"=>"LAXMAN", "30"=>"KISHAN", 
                                        "80"=>"RAGHAV")
$array3 = ("30"=>"LAXMAN", "80"=>"RAGHAV")
Output :
Array
(
    [20] => LAXMAN
    [30] => RAVI
    [40] => KISHAN
    [50] => RISHI
)

Input :
$array1 = ("10"=>"RAM", "20"=>"LAXMAN", "30"=>"RAVI", 
                      "40"=>"KISHAN", "50"=>"RISHI");
$array2 = ("10"=>"LAXMAN", "40"=>"RAGHAV", "40"=>"KISHAN");
Output :
Array
(
    [10] => RAM
    [20] => LAXMAN
    [30] => RAVI
    [50] => RISHI
)

Below program illustrates the working of array_diff_key() in PHP:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// PHP code to illustrate the 
// array_diff_assoc() function
  
// Input Arrays
$array1 = array("10"=>"RAM", "20"=>"LAXMAN", "30"=>"RAVI"
                            "40"=>"KISHAN", "50"=>"RISHI");
$array2 = array("10"=>"RAM", "70"=>"LAXMAN"
                "30"=>"KISHAN", "80"=>"RAGHAV");
$array3 = array("30"=>"LAXMAN", "80"=>"RAGHAV");
  
print_r(array_diff_assoc($array1, $array2, $array3));
  
?>

chevron_right


Output:

Array
(
    [20] => LAXMAN
    [30] => RAVI
    [40] => KISHAN
    [50] => RISHI
)

Reference:
http://php.net/manual/en/function.array-diff-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.