Current Location: Home> Function Categories> array_diff_ukey

array_diff_ukey

Use callback function to compare key names to calculate the difference set of arrays
Name:array_diff_ukey
Category:Array
Programming Language:php
One-line Description:Compare arrays and return the difference set (compare only key names, use user-defined key names comparison function).

array_diff_ukey function

Applicable to PHP version: PHP 5.3.0 and above

Function Description: The array_diff_ukey function is used to compare the key names of two or more arrays, returning key names that exist in the first array but do not exist in other arrays. This function uses a user-defined callback function to compare key names.

Function syntax: array_diff_ukey(array $array1, array $array2, array ...$arrays, callable $key_compare_func): array

parameter:

  • $array1 : The first array, the benchmark array for comparison.
  • $array2 : The second array, the target array compared to the first array.
  • $arrays : Other optional arrays, further compared to the first array.
  • $key_compare_func : a user-defined callback function used to compare the sizes of two key names. This function must return an integer value:
    • Less than 0: means that the first key name is less than the second.
    • Equal to 0: means that the two key names are equal.
    • Greater than 0: means that the first key name is greater than the second.

Return value: Returns an array containing all key names that exist in the first array but not in other arrays.

Example:

  $array1 = [
      'a' => 1,
      'b' => 2,
      'c' => 3,
      'd' => 4
  ];
  $array2 = [
      'a' => 1,
      'b' => 2,
      'e' => 5
  ];
<p>function compare_keys($key1, $key2) {<br>
return strcmp($key1, $key2);<br>
}</p>
<p>$result = array_diff_ukey($array1, $array2, &#39;compare_keys&#39;);<br>
print_r($result);<br>

Description of the sample code: In this example, two arrays $array1 and $array2 are compared. We have customized a function called compare_keys to compare the order of key names. After comparison, array_diff_ukey returns all key names that exist in $array1 but not in $array2 and is sorted by the rules of the compare_keys function.

Similar Functions
Popular Articles