Home > Backend Development > PHP Tutorial > How Can I Efficiently Identify Shared Elements Between Two PHP Arrays?

How Can I Efficiently Identify Shared Elements Between Two PHP Arrays?

Susan Sarandon
Release: 2024-12-04 04:40:15
Original
758 people have browsed it

How Can I Efficiently Identify Shared Elements Between Two PHP Arrays?

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);
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template