array_intersect_ukey(): intersection between two arrays considering keys for checks through callback function

This function takes two or more arrays as input and then returns the result array as intersection considering keys.
$new_array = array_intersect_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 present in $array2 considering keys only.

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('1st'=> 'First','Two'=>'2nd','Three'=>'3rd','Fourth');

$result=array_intersect_ukey($first,$second,"my_function");
while (list ($key, $val) = each ($result)) {
echo "$key -> $val <br>";
}
Output is here.
Two -> Second 
Three -> Third 
0 -> Fourth 
Keys of the first index are retained. ( no re-indexing done here) .

Example 2: Using array_intersect_ukey() for Case-Insensitive Key Comparison

This example demonstrates how to use array_intersect_ukey() for case-insensitive key comparison, which is useful in scenarios where key case consistency isn't guaranteed.

function key_compare_func($key1, $key2) {
    return strcasecmp($key1, $key2);
}

$array1 = array('a' => 100, 'b' => 200, 'C' => 300);
$array2 = array('A' => 100, 'b' => 200, 'c' => 300);

$result = array_intersect_ukey($array1, $array2, 'key_compare_func');

print_r($result);

Output:

Array
(
    [a] => 100
    [b] => 200
    [C] => 300
)

Example 3: Filtering Arrays Based on Prefix in Keys

Filter two arrays to find common keys starting with a specific prefix, using a custom comparison function.

function prefix_compare($key1, $key2) {
    if (strpos($key1, 'pre_') === 0 && $key1 === $key2) {
        return 0;
    }
    return $key1 >= $key2 ? 1 : -1;
}

$array1 = array('pre_first' => 'apple', 'pre_second' => 'banana', 'post_third' => 'cherry');
$array2 = array('pre_first' => 'apple', 'second' => 'banana', 'third' => 'cherry');

$result = array_intersect_ukey($array1, $array2, 'prefix_compare');

print_r($result); 

Output:

Array
(
    [pre_first] => apple
)

Difference between arrays considering values
Array REFERENCE
Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com











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