PHP array_diff_key() Function
Quick summary: The PHP array_diff_key() function compares the keys of two (or more) arrays, and returns the differences.
PHP array_diff_key() Syntax
array_diff_key(array $array, array ...$arrays): array
PHP
PHP array_diff_key() Basic examples
$a = ['a'=>1,'b'=>2];
$b = ['a'=>3];
print_r(array_diff_key($a,$b));
PHP
Output:
Array ( [b] => 2 )
Compares only keys and returns differences.
PHP array_diff_key() Real-world usage
$defaults = ['host'=>'localhost','port'=>3306];
$config = ['host'=>'127.0.0.1'];
print_r(array_diff_key($defaults,$config));
PHP
Output:
Array ( [port] => 3306 )
Find missing configuration keys.
PHP array_diff_key() Edge cases
$a = ['1'=>true];
$b = [1=>false];
print_r(array_diff_key($a,$b));
PHP
Output:
Array ( )
String and integer keys may be treated as identical.
PHP array_diff_key() Common mistakes
Expecting value comparison
array_diff_key() ignores values.
Incorrect
array_diff_key(['a'=>1],['a'=>2]);
Correct
array_diff_assoc(['a'=>1],['a'=>2]);
Use array_diff_assoc() if values must be compared.
PHP array_diff_key() Frequently Asked Questions
What does array_diff_key() do?
Compares arrays by keys only.
Use case?
Filtering keys.
Ignores values?
Yes.
Return type?
Array.
Common mistake?
Expecting value comparison.
Performance?
Fast.
Safe?
Yes.
Alternative?
array_intersect_key().
Handles nested arrays?
No.
Case sensitive?
Yes.
Best practice?
Normalize keys.
Used in configs?
Yes.