Identifying Elements Shared by Flat Arrays
Given two flat arrays, a need may arise to determine if any elements from the first array exist within the second. In PHP, this task can be efficiently accomplished utilizing the array_intersect() function.
In the example provided, we have two arrays: $people = [3, 20] and $criminals = [2, 4, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]. Our objective is to ascertain if any of the individuals listed in $people are present in the $criminals array.
Solution using array_intersect()
The array_intersect() function takes multiple arrays as input and returns an array containing only the elements that are common to all input arrays. In our case, to check if any elements from $people exist in $criminals, we can use the following code:
$intersection = array_intersect($people, $criminals);
The $intersection array will contain any elements from $people that also appear in $criminals. In this example, since 20 is present in both arrays, $intersection will be [20].
Verifying Intersecting Elements
To determine if any element from $people is in $criminals, we can check if the $intersection array is empty. If it is, then no elements from $people are present in $criminals. Otherwise, at least one element is shared between the two arrays.
$peopleContainsCriminal = !empty($intersection);
In the example, $peopleContainsCriminal will evaluate to true because 20 is present in both arrays.
The above is the detailed content of How Can I Efficiently Identify Shared Elements Between Two PHP Arrays?. For more information, please follow other related articles on the PHP Chinese website!