array_intersect_uassoc() finds matching entries using normal value comparison and a user-supplied callback for keys.
$first = ['A' => 'red', 'b' => 'green'];
$second = ['a' => 'red', 'B' => 'blue'];
$result = array_intersect_uassoc($first, $second, 'strcasecmp');
print_r($result);Only the key comparison is delegated to the callback.
$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. 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");
foreach ($result as $key => $val) {
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) .$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 )
$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 )
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.