The array_diff_key Function
The array_diff_key
function compares the keys of two or more arrays and returns an array containing the elements from the first array whose keys are not present in the other arrays. The comparison is based only on keys; the values of the elements are not taken into account.
Syntax
array_diff_key(array $array1, array $array2 [, array $...]): array
Example
Let's compare two arrays by keys:
<?php
$arr1 = ['a' => 1, 'b' => 2, 'c' => 3];
$arr2 = ['a' => 4, 'd' => 5];
$res = array_diff_key($arr1, $arr2);
print_r($res);
?>
Code execution result:
['b' => 2, 'c' => 3]
Example
Comparing three arrays by keys:
<?php
$arr1 = [1 => 'a', 2 => 'b', 3 => 'c'];
$arr2 = [1 => 'd', 4 => 'e'];
$arr3 = [5 => 'f', 2 => 'g'];
$res = array_diff_key($arr1, $arr2, $arr3);
print_r($res);
?>
Code execution result:
[3 => 'c']
Example
Using numeric and string keys:
<?php
$arr1 = ['color' => 'red', 1 => 'a', 2 => 'b'];
$arr2 = [1 => 'c', 'size' => 'XL'];
$res = array_diff_key($arr1, $arr2);
print_r($res);
?>
Code execution result:
['color' => 'red', 2 => 'b']
See Also
-
the
array_diff
function,
which compares arrays by values -
the
array_intersect_key
function,
which returns matching keys