array_intersect_uassoc(): intersection between two arrays considering additional key checks through callback function

This function takes two or more arrays as input and then returns the result array as intersection considering both values and keys.
$new_array = array_intersect_uassoc ($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 also.

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','2nd'=>'Second','Three'=>'Third','Fourth');

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

Example: Comparing Arrays with Case-Insensitive Keys

$array1 = ["a" => "green", "B" => "red", "C" => "blue"];
$array2 = ["A" => "green", "b" => "yellow"];
$result = array_intersect_uassoc($array1, $array2, "strcasecmp");
print_r($result);  // Output: Array ( [a] => green )

Example: Custom Key Comparison Function

$array1 = ["apple" => 1, "banana" => 2];
$array2 = ["banana" => 2, "grape" => 3];
$result = array_intersect_uassoc($array1, $array2, function($key1, $key2) {
    return $key1 <=> $key2;  // Custom comparison
});
print_r($result);  // Output: Array ( [banana] => 2 )

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