Saturday, February 7, 2026
HomeLanguagesPHP array_diff_key() Function

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 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

RELATED ARTICLES

Most Popular

Dominic
32491 POSTS0 COMMENTS
Milvus
126 POSTS0 COMMENTS
Nango Kala
6863 POSTS0 COMMENTS
Nicole Veronica
11987 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12076 POSTS0 COMMENTS
Shaida Kate Naidoo
6996 POSTS0 COMMENTS
Ted Musemwa
7238 POSTS0 COMMENTS
Thapelo Manthata
6947 POSTS0 COMMENTS
Umr Jansen
6933 POSTS0 COMMENTS