Home >>PHP Array Functions >PHP array_diff_key() Function

PHP array_diff_key() Function

PHP array_diff_key() Function

PHP array_diff_key() Function is used to get the difference between one or more given arrays. It compares two arrays on the basis of their key value and returns the elements that are present in the first array but not in the other input arrays. It can take any number of arrays as parameters needed to be compared. It compares the key of the first given array with rest of the arrays and returns an array containing all the entries from $array1 that are not present in any other arrays.

Syntax:

array_diff_key($array1, $array2, $array3, ...);

Parameter Values

Parameter Description
array1 This is a required parameter. This parameterdefines the array to compare from.
array2 This is a required parameter. This parameter definesan array to compare against.
array3 This is an optional parameter. This parameter defines more arrays to compare against

Here is an example of array_diff_key() function in PHP:

<html>
<body>
<pre>
<?php
$x=array("a"=>"1","b"=>"2","c"=>"3");
$y=array("a"=>"1","c"=>"2","d"=>"3");
$result=array_diff_key($x,$y);
print_r($result);
?>
</pre>
</body>
</html>
Output:
Array
(
    [b] => 2
)

Example 2:

<html>
<body>
<pre>
<?php
$x=array("a"=>"1","b"=>"2","c"=>"3");
$z=array("a"=>1,"b"=>"3","c"=>"45","d"=>"11");
$result=array_diff_key($x,$z);  // only compares keys not values
print_r($result);
?>
</pre>
</body>
</html>
Output:
Array()

No Sidebar ads