In PHP, there are many functions for handling array intersections. Among them, array_intersect_assoc and array_intersect_uassoc are often confused due to their similar functionalities. Both are used to calculate the intersection of multiple arrays, but they behave differently when comparing array keys. This article will explain the differences between these two functions and provide practical usage advice.
array_intersect_assoc(array $array1, array $array2, array ...$arrays): array
Calculates the intersection of arrays, comparing both values and keys strictly. Key comparison uses PHP's default equality check (i.e., ==).
array_intersect_uassoc(array $array1, array $array2, array ...$arrays, callable $key_compare_func): array
Similar to array_intersect_assoc, but key comparison is performed using a user-defined callback function $key_compare_func instead of the default equality check.
Feature | array_intersect_assoc | array_intersect_uassoc |
---|---|---|
Compare values | Yes | Yes |
Compare keys | Yes | Yes |
Key comparison method | Default key comparison (==) | User-defined callback function |
Support custom comparison? | No | Yes |
Usage example | No comparison function required | Requires a callback function to compare keys |
<?php
$array1 = ["a" => "green", "b" => "brown", "c" => "blue", "1" => "red"];
$array2 = ["a" => "green", "1" => "red", "b" => "brown", "c" => "blue"];
<p>// array_intersect_assoc compares both keys and values directly<br>
$result_assoc = array_intersect_assoc($array1, $array2);<br>
// Output: ["a" => "green", "b" => "brown", "c" => "blue"]<br>
print_r($result_assoc);</p>
<p>// Custom comparison function, case-sensitive key comparison<br>
function key_compare_func($key1, $key2) {<br>
return strcmp($key1, $key2);<br>
}</p>
<p>$array3 = ["A" => "green", "b" => "brown", "c" => "blue"];<br>
$result_uassoc = array_intersect_uassoc($array1, $array3, "key_compare_func");<br>
// Output: ["b" => "brown", "c" => "blue"]<br>
print_r($result_uassoc);<br>
?><br>
When you only need to check if array keys and values are equal, and you don’t need custom rules for key comparison (e.g., case-insensitive or type conversion), it’s a concise and efficient choice.
Use array_intersect_uassoc:
When you need special rules for key comparison, such as:
Case sensitivity
More complex comparison logic
Keys are custom objects or complex types
In these cases, you can provide a callback function for flexible key comparison rules.
array_intersect_assoc performs array intersections based on default key and value comparisons.
array_intersect_uassoc provides a more flexible key comparison mechanism, allowing users to define custom comparison logic.
Choose the appropriate function according to your business needs. Selecting the right function can result in more robust and maintainable code.