Skip to content
Related Articles
Open in App
Not now

Related Articles

PHP | array_diff_key() Function

Improve Article
Save Article
  • Last Updated : 26 Oct, 2020
Improve Article
Save Article

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

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!