PHP array_diff_key Function
last modified March 13, 2025
The PHP array_diff_key
function compares array keys and returns
the differences. It's useful for finding keys that exist in one array but
not others.
Basic Definition
The array_diff_key
function compares keys of multiple arrays.
It returns an array containing all entries from the first array whose keys
are not present in any of the other arrays.
Syntax: array_diff_key(array $array1, array ...$arrays): array
.
The comparison is based on keys only, not values. Key types must match.
Basic array_diff_key Example
This shows a simple comparison between two arrays with different keys.
<?php $array1 = ['a' => 1, 'b' => 2, 'c' => 3]; $array2 = ['a' => 4, 'd' => 5]; $result = array_diff_key($array1, $array2); print_r($result);
Output: Array ( [b] => 2 [c] => 3 )
. The function returns
elements from $array1 whose keys ('b' and 'c') don't exist in $array2.
Comparing Multiple Arrays
You can compare the first array against several other arrays at once.
<?php $array1 = ['red' => '#FF0000', 'green' => '#00FF00', 'blue' => '#0000FF']; $array2 = ['red' => '#FF0000', 'yellow' => '#FFFF00']; $array3 = ['green' => '#00FF00', 'cyan' => '#00FFFF']; $result = array_diff_key($array1, $array2, $array3); print_r($result);
Output: Array ( [blue] => #0000FF )
. Only 'blue' key exists
in $array1 but not in $array2 or $array3. Values are irrelevant.
Numeric Key Comparison
The function works with numeric keys just like with string keys.
<?php $array1 = [10 => 'A', 20 => 'B', 30 => 'C']; $array2 = [10 => 'X', 40 => 'Y']; $result = array_diff_key($array1, $array2); print_r($result);
Output: Array ( [20] => B [30] => C )
. The keys 20 and 30
from $array1 don't exist in $array2, so their elements are returned.
Mixed Key Types
The function distinguishes between different key types (string vs integer).
<?php $array1 = ['10' => 'String key', 10 => 'Integer key', '20' => 'Twenty']; $array2 = [10 => 'Integer value']; $result = array_diff_key($array1, $array2); print_r($result);
Output: Array ( [10] => String key [20] => Twenty )
. The
string key '10' is different from integer key 10, so it's included.
Empty Array Behavior
When comparing with empty arrays, all keys from the first array are returned.
<?php $array1 = ['a' => 1, 'b' => 2]; $array2 = []; $result = array_diff_key($array1, $array2); print_r($result);
Output: Array ( [a] => 1 [b] => 2 )
. Since $array2 has no
keys, all keys from $array1 are considered different and returned.
Best Practices
- Key Consistency: Maintain consistent key types for reliable comparisons.
- Multiple Arrays: Compare against several arrays at once for efficiency.
- Type Awareness: Remember that '1' and 1 are different keys.
- Performance: For large arrays, consider key extraction first.
Source
PHP array_diff_key Documentation
This tutorial covered the PHP array_diff_key
function with
practical examples showing its usage for array key comparison scenarios.
Author
List all PHP Array Functions.