In this tutorial, you shall learn about PHP array_diff_ukey() function which can compute the difference of an array against other arrays based on keys where comparison of keys is done based on user defined callback function, with syntax and examples.
PHP array_diff_ukey() Function
PHP array_diff_ukey() function computes the difference of an array against other arrays based on keys. The logic for comparison of keys is done using user defined callback function.
In this tutorial, we will learn the syntax of array_diff_ukey(), and how to use this function to find the difference of an array from other arrays based on keys, covering different scenarios based on array type and arguments.
Syntax of array_diff_ukey()
The syntax of PHP array_diff_ukey() function is
array_diff_ukey ( array $array1 , array $array2 [, array $... ], callable $key_compare_func ) : array
where
| Parameter | Description |
|---|---|
| array1 | [mandatory] Array of interest. Compare the keys/index of this array against other arrays’. |
| array2 | [mandatory] Array of reference. The keys of this array are used to comparison against. |
| … | [optional] More arrays, along with array2, to compare against. |
| key_compare_func | This function must return an integer: 1. less than zero, if first argument is less than second argument. 2. equal to zero, if first argument equals second argument. 3. greater than zero, if first argument is greater than second argument. |
Return Value
The array_diff_ukey() function returns an array of elements whose keys are present in $array1 but not present in $array2 or other arrays(if provided).
Examples
1. Compute difference of Arrays (based on Keys)
In this example, we will take an associative array, array1, with key-value pairs; compare it against another array, array2; and find their difference using array_diff_ukey() function.
PHP Program
<?php
function key_compare_func($a, $b) {
if ($a === $b) {
return 0;
}
return ($a > $b)? 1:-1;
}
$array1 = array('a'=>'apple', 'b'=>'banana', 'c'=>'cherry');
$array2 = array('a'=>'avocado', 'c'=>'citrus');
$result = array_diff_ukey($array1, $array2, "key_compare_func");
print_r($result);
?>
Output
