Checking if ANY elements of a flat array are in another flat array
Determining whether any value from one collection exists within another is a fundamental operation in data processing. In the specific scenario provided, you have two arrays: $people, containing IDs 3 and 20, and $wantedCriminals, which holds a list including 20. The goal is to return a boolean indicating if there is at least one intersection between these two sets of values.
While this might seem trivial for small datasets, the approach you choose dictates performance characteristics that scale significantly as data grows. You need to distinguish between iterating linearly through both arrays and leveraging built-in functions optimized for membership testing.
The Naive Iterative Approach
The most intuitive solution is to write a manual loop or use array_any logic (available in PHP 8.1+ via array_any). However, the classic approach often seen involves nested loops or a single pass with strict comparison.
If you iterate through $people and check every element against $wantedCriminals using in_array, you are effectively performing an $O(n \times m)$ operation, where $n$ is the size of the first array and $m$ is the size of the second. In your example, checking if 3 exists in the large criminal list takes time proportional to the length of that list. Checking 20 takes similar time.
$people = [3, 20];
$wantedCriminals = [2, 4, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
$found = false;
foreach ($people as $person) {
if (in_array($person, $wantedCriminals)) {
$found = true;
break; // Stop immediately once a match is found
}
}
This method works perfectly fine for the small arrays in your source material. The break statement is crucial here; without it, you would continue checking even after finding 20, wasting CPU cycles on unnecessary comparisons. If you are running this logic inside a tight loop processing thousands of records, this $O(n \times m)$ complexity can become a bottleneck.
Leveraging Built-in Set Operations
PHP provides higher-level functions that abstract away the iteration logic. The function array_any (introduced in PHP 8.1) allows you to express "does any element satisfy a condition?" directly. You can pass a callback that checks for existence using in_array.
// PHP 8.1+
$found = array_any($people, fn ($person) => in_array($person, $wantedCriminals));
While this improves readability, the underlying complexity remains dependent on how in_array behaves. If you can afford a small upfront cost to optimize lookups, a different strategy emerges.
Using an Associative Array for O(1) Lookups
The most performant pattern involves transforming the larger array into a key-value mapping where the values themselves act as keys. By converting $wantedCriminals into an associative array using array_flip, you change the lookup complexity from $O(m)$ to $O(1)$.
Once flipped, checking for existence becomes a simple isset or direct array access check. This transforms the overall algorithm to $O(n + m)$, where you iterate through both arrays once during the setup and then perform constant-time checks for each element in $people.
$wantedCriminals = [2, 4, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
// Flip the array: keys become values, and values become keys (assuming unique values)
$wantedSet = array_flip($wantedCriminals);
// Check if any value from $people exists as a key in $wantedSet
$found = false;
foreach ($people as $person) {
if (isset($wantedSet[$person])) {
$found = true;
break;
}
}
There is a caveat here: array_flip will throw an error or overwrite keys if $wantedCriminals contains duplicate values. In your specific example, all values are unique integers, so this approach is safe. If the input data could contain duplicates (e.g., ['20', '20']), you would need to use array_column with flags or a more robust set implementation to avoid losing data integrity during the flip.
Summary of Trade-offs
For static checks on small datasets, the initial in_array loop is perfectly adequate and requires zero extra memory allocation. However, if this logic resides in a high-throughput service layer, converting the larger list into an associative map provides significant speed improvements as the dataset scales. The cost is the $O(m)$ space required to build the lookup table and the slight overhead of array_flip.
Always ensure you break out of the loop immediately upon finding a match, regardless of the method used, to prevent unnecessary processing once the condition "any element exists" has been satisfied.
