Using array_diff_ukey() with a Callback Function to Compute Array Differences by Keys in PHP
This article explains how the PHP function array_diff_ukey() compares array keys using a user‑defined callback, details each parameter and return value, and provides a complete example showing the callback implementation, input arrays, and the resulting diff output.
The array_diff_ukey() function returns an array containing the entries from $array1 whose keys are not present in any of the other arrays passed to the function. Unlike array_diff() , the comparison is performed on keys rather than values, and a user‑provided callback determines the ordering of the keys.
Parameters
array1 (required): The first array to compare.
array2 (required): The second array to compare against array1 . Additional arrays can be supplied as further arguments.
key_compare_func (required): A callable that receives two keys and must return an integer less than, equal to, or greater than zero when the first key is considered respectively less than, equal to, or greater than the second key.
Return value
The function returns an array containing all key‑value pairs from array1 whose keys are not found in any of the other arrays after being evaluated by the callback.
Example
$key2) {
return 1;
} else {
return -1;
}
}
$array1 = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan' => 8);
var_dump(array_diff_ukey($array1, $array2, 'key_compare_func'));
?>Output
array(2) {
["red"]=> int(2)
["purple"]=> int(4)
}This output shows that the keys red and purple exist in $array1 but not in $array2 , demonstrating how array_diff_ukey() isolates differing keys using the custom comparison function.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.