PHP
Find Differences Between Two Associative Arrays by Keys
Efficiently compare two associative arrays in PHP to identify entries that exist in one but not the other, based solely on their keys.
<?php
$array1 = [
'apple' => 1,
'banana' => 2,
'orange' => 3,
'grape' => 4
];
$array2 = [
'banana' => 2,
'orange' => 5,
'kiwi' => 6,
'grape' => 4
];
// Keys in array1 but not in array2
$keysOnlyInArray1 = array_diff_key($array1, $array2);
print_r($keysOnlyInArray1);
// Keys in array2 but not in array1
$keysOnlyInArray2 = array_diff_key($array2, $array1);
print_r($keysOnlyInArray2);
// Combined unique keys from both arrays (useful for identifying added/removed items)
$allUniqueKeys = array_merge_recursive($keysOnlyInArray1, $keysOnlyInArray2);
print_r($allUniqueKeys);
/* Expected Output for keysOnlyInArray1:
Array
(
[apple] => 1
)
Expected Output for keysOnlyInArray2:
Array
(
[kiwi] => 6
)
Expected Output for allUniqueKeys:
Array
(
[apple] => 1
[kiwi] => 6
)
*/
How it works: The `array_diff_key` function is designed to compare two (or more) arrays and return the entries from the first array whose keys are not present in any of the other arrays. This is incredibly useful for tasks like comparing two versions of a configuration array, identifying new or removed items from a list, or synchronizing data where keys represent unique identifiers. It focuses purely on key existence, ignoring the associated values.