array_diff_ukey(): Difference between two arrays comparing keys through callback function

This function takes two or more arrays as input and then returns the result array as difference.
$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.

Returns all elements of $array1 which are not present in $array2 considering keys. Keys comparison is done through call-back function my_function().

Example with two arrays

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');

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.

Example 2

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);
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.
We are comparing keys only ( not values ) so Third =>33 is matched with Three=>3 so it not appearing in output (as the difference only shown). Similarly FourthH=>4 is not matched with Four=>4 as index or key is compared ( which is not matching ) though the value 4 is matching. Hence it is included in the output.
Subscribe to our YouTube Channel here


* indicates required
Subscribe to plus2net

    Post your comments , suggestion , error , requirements etc here .

    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2022 All rights reserved worldwide Privacy Policy Disclaimer