In PHP, there are many functions for handling array intersections. Among them, array_intersect_assoc and array_intersect_uassoc are two functions that are often confused but share very similar functionality. Both are used to calculate the intersection of multiple arrays, but they differ in how they compare array keys. This article will explain the differences between these two functions in detail and provide practical usage recommendations.
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 done 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 (==) | Comparison via user-defined callback function |
Support Custom Comparison? | No | Yes |
Usage Example | No need to pass a comparison function | Requires passing a callback function for key comparison |
<?php
$array1 = ["a" => "green", "b" => "brown", "c" => "blue", "1" => "red"];
$array2 = ["a" => "green", "1" => "red", "b" => "brown", "c" => "blue"];
<p>// array_intersect_assoc compares 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 compare whether array keys and values are equal and don’t require custom rules for key comparison (e.g., case-insensitivity or type conversion), this is a simple and efficient choice.
When you need a special key comparison, such as:
Case-sensitive comparison
More complex comparison logic
Keys are custom objects or complex types
In this case, you can pass a callback function to implement flexible key comparison rules.
array_intersect_assoc is an array intersection based on default key and value comparison.
array_intersect_uassoc offers a more flexible key comparison mechanism, allowing custom comparison logic.
Choose the appropriate function based on your business requirements. Using the right function ensures more robust and maintainable code.