PHP compare two arrays and get the matched values not the difference
Developers often reach for array_diff() when they need to analyze relationships between datasets, but it frequently yields the opposite of what is needed. As shown in common queries, this function returns elements that exist in one array but not the other. In your specific case, you are looking for the intersection: the subset of values present in both $array1 and $array2.
For simple value comparisons where keys don't matter, array_intersect() is the direct solution. It returns an array containing all entries from the first array that are also present in the second. Using your provided example:
$array1 = ["**alpha**", "omega", "**bravo**", "**charlie**", "**delta**", "**foxfrot**"];
$array2 = ["**alpha**", "gamma", "**bravo**", "x-ray", "**charlie**", "**delta**", "halo", "eagle", "**foxfrot**"];
$result = array_intersect($array1, $array2);
// Result: ["**alpha**", "**bravo**", "**charlie**", "**delta**", "**foxfrot**"]
This approach is efficient and readable. However, relying solely on array_intersect() can introduce subtle bugs in complex applications due to how PHP handles string comparison and key preservation.
String Comparison Pitfalls
In the example above, the values are wrapped in bold markdown syntax (**alpha**). In a real-world scenario, these would be plain strings like "alpha". If you were comparing actual data, array_intersect() performs a loose comparison by default using ==. This means it checks for equality of value rather than identity.
While this works fine for simple types like integers and standard strings, it becomes problematic with floats or strings representing numbers. For instance, the string "1e6" is loosely equal to the integer 1000000, but they are not identical values. If your application requires strict type safety, you should use the third parameter of array_intersect() to force a strict comparison:
$result = array_intersect($array1, $array2, true);
This ensures that "1e6" and 1000000 are treated as different values. This distinction is critical when processing financial data or scientific measurements where precision matters.
Handling Associative Arrays
A frequent source of confusion arises when dealing with associative arrays (where keys are not simple integers). The intersection logic for such arrays can be counterintuitive. array_intersect() preserves the keys from the first array passed to it. It filters those keys based on whether their associated values exist in any of the subsequent arrays.
Consider this scenario:
$users = [1 => 'Alice', 2 => 'Bob'];
$active_users = ['Alice' => true, 'Charlie' => true];
// Returns [1 => 'Alice'] because the value 'Alice' exists in $active_users
// The key is preserved from $users, not taken from $active_users.
$result = array_intersect($users, $active_users);
If your goal is to merge keys or ensure a specific key format, this behavior might require post-processing. You may need to re-index the result using array_values() if sequential keys are required for downstream logic.
Performance Considerations
For small to medium-sized datasets, array_intersect() is fast because it leverages optimized internal implementations in PHP's SAPI. However, as array sizes grow into the millions of elements, linear scanning becomes a bottleneck. In high-performance contexts involving massive logs or large configuration dumps, you might consider converting arrays to SplObjectStorage or using hash tables manually for O(1) lookups, though this adds significant complexity and memory overhead. For 95% of use cases, sticking with array_intersect() is the pragmatic choice.
Conclusion on Best Practices
When comparing arrays to find common elements, defaulting to array_diff() is a common mistake that leads to logic errors. Always verify whether you need the difference or the intersection before selecting your function. If strict type safety is required, explicitly pass true as the third argument to array_intersect(). Understanding how keys are preserved versus how values are matched ensures that your data processing pipelines remain robust against edge cases involving floats and associative structures.
