$new_array = array_diff_ukey ($array1, $array2,....,my_function());
my_function() : is the callback function to return integer less than , equal to or greater than zero after comparing the keys. function my_function($a, $b)
{
if ($a === $b) {
return 0;
}
return ($a > $b)? 1:-1;
}
$first=array('One' =>'First','Two'=>'Second','Three'=>'Third','Fourth');
$second=array('One'=> 'First','Fourth','2nd');
$result=array_diff_ukey($first,$second,"my_function");
while (list ($key, $val) = each ($result)) {
echo "$key -> $val <br>";
}
Output is here.
Two -> Second
Three -> Third
Keys of the first index are retained. ( no re-indexing done here) . The element with value Third is included in output as the index or key is not matching with $second array though the value is matching.
function my_function($a, $b) {
static $match = [
'First' => 'One',
'Second' => 'Two',
'Third' => 'Three',
'Fourth' => 'Four',
'Fifth' => 'five'
];
if (isset($match[$a])) {
return $match[$a] != $b;
} elseif(isset($match[$b])) {
return $match[$b] != $a;
}
return true;
// 0 returned if there is a match and 1 if no match
}
$first=array('First' =>1,'Second'=>2,'Third'=>33,'FourthH'=>4,'Fifth'=>5);
$second=array('One'=>1,'Two'=>2,'Three'=>3,'Four'=>4);
$result=array_diff_ukey($first,$second,"my_function");
while (list ($key, $val) = each ($result)) {
echo "$key -> $val <br>";
}
Output is here
FourthH -> 4
Fifth -> 5
The function my_function() checks the entries and returns 0 if there is a match and returns 1 if no match is found.You can use array_diff_ukey() to perform case-insensitive key comparison by defining a custom comparison function:
$arr1 = array("Key1" => 1, "Key2" => 2);
$arr2 = array("key1" => 1, "key3" => 3);
function caseInsensitiveCompare($key1, $key2) {
return strcasecmp($key1, $key2);
}
$result = array_diff_ukey($arr1, $arr2, "caseInsensitiveCompare");
print_r($result); // Outputs: Array ( [Key2] => 2 )
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.