PHP array_diff_ukey() Function

What is PHP array_diff_ukey() Function?

The array_diff_ukey() function compares an array with one or more arrays with a callback function and returns an array which contains keys that exists in first array but not exists in other arrays.

Syntax:

array_diff_ukey(array1, array2, array3, …, key_compare_function)

Parameters:

The Function has 3 required parameters and any number of optional parameters-

array1 (Required): This is the first array whose keys the function checks whether exist in other arrays or not.

array2 (Required): It is another array whose keys the function compares with the first array. Check example 1.

array3, … (Optional): It is one or more arrays whose keys the function compares with the first array. Check example 2.

key_compare_function (Required): It is the callback function that determines the comparison of the two arrays. The function must return the followings-

  • 0 if both arguments are equal.
  • Greater than 0 if first argument is greater than the second one.
  • Less than 0 if the first argument is less than the second one.

Return Values:

The function returns an array.

Examples:

Example 1:

<?php
function key_compare_function1($a,$b){
  if ($a === $b){
    return 0;
    }
    return ($a>$b) ? 1 : -1;
}
$arr1 = array("c" => "CSS", "h" => "HTML", "p" => "PHP");
$arr2 = array("c" => "CSS", "h" => "HTML", "j" => "JavaScript");

$result=array_diff_ukey($arr1,$arr2,"key_compare_function1");
print_r($result);
?>

Output:

Array ( [p] => PHP )

Example 2:

<?php
function key_compare_function3($a,$b){
  if ($a === $b){
    return 0;
    }
    return ($a>$b) ? 1 : -1;
}
$arr1 = array("c" => "CSS", "h" => "HTML", "j" => "JavaScript", "p" => "PHP");
$arr2 = array("c" => "CSS", "h" => "HTML");
$arr3 = array("h" => "HTML", "m" => "MySQL");

$result=array_diff_ukey($arr1, $arr2, $arr3, "key_compare_function3");
print_r($result);
?>

Output:

Array ( [j] => JavaScript [p] => PHP )

Example 3:

<?php
function key_compare_function2($a,$b){
  if ($a === $b){
    return 0;
    }
    return ($a>$b) ? 1 : -1;
}
$arr1 = array("c" => "CSS", "h" => "HTML", "p" => "PHP");
$arr2 = array("C" => "CSS", "H" => "HTML", "j" => "JavaScript");

$result=array_diff_ukey($arr1, $arr2, "key_compare_function2");
print_r($result);
?>

Output:

Array ( => CSS [h] => HTML [p] => PHP )

Notes on array_diff_ukey() Function:

  • The function considers keys as case sensitive. So, key “c” is different than the key “C”. Check example 3.

Caution:

  • When the callback function may return a non-integer function, it internally casts the value to integer. So, 1.1 becomes 1, .9 becomes 0.

PHP Version Support:

PHP 5 >= 5.1.0, PHP 7, PHP 8

Summary: PHP array_diff_ukey() Function

The array_diff_ukey() is one of the built-in PHP array functions that compares keys of one array with other that of other arrays using a key comparison callback function.

Reference:

https://www.php.net/manual/en/function.array-diff-key.php