The Wayback Machine - https://web.archive.org/web/20250114114609/https://www.geeksforgeeks.org/php-array_diff_key-function/
Open In App

PHP array_diff_key() Function

Last Updated : 20 Jun, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 their 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 the 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
    [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:




<?php
  
// PHP code to illustrate the 
// array_diff_key() 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_key($array1, $array2, $array3));
  
?>


Output:

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

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

Become a Full-Stack Developer and also get 90% fee refund on completing 90% course in 90 days! Take the Three 90 Challenge today.

After successfully processing refunds worth over INR 5 Cr, GeeksforGeeks is back with the Three 90 challenge and this is your chance to upskill and get 90% refund. What more motivation do you need? Start the challenge right away!


Next Article
Article Tags :

Similar Reads

three90RightbarBannerImg