Home > Backend Development > PHP Tutorial > Is the number of intersections in the two arrays equal?

Is the number of intersections in the two arrays equal?

WBOY
Release: 2016-07-06 13:52:30
Original
1251 people have browsed it

Count whether the number of intersections in the two arrays is equal. Thank you

====================================
Supplement:
$a= array('1','2');
$b=array('1','2','3','2');

In array a, 1 and 2 appear once each
, but in array b, 1 appears once and 2 appears twice

The intersection is 1 and 2. Now I want to know whether the number of occurrences is equal

Reply content:

Count whether the number of intersections in the two arrays is equal. Thank you

====================================
Supplement:
$a= array('1','2');
$b=array('1','2','3','2');

In array a, 1 and 2 appear once each
, but in array b, 1 appears once and 2 appears twice

The intersection is 1 and 2. Now I want to know whether the number of occurrences is equal

Since it is an intersection, it should be equal. The elements that both arrays have are called intersections. You don’t understand the concept of sets. Sets do not allow duplicate elements.

The basic concept of sets is misunderstood. The elements in a set are mutually exclusive, so they will only appear once. Correspondingly, the intersection elements will only appear once in each set.

Depending on the needs of your example, just traverse the calculated intersection to make a judgment.

<code>$arr1 = [1,2];
$arr2 = [1,2,3,2];

$intersect = array_intersect($arr1, $arr2);

$result = array();
foreach ($intersect as $item) {
    $result[$item] = array('arr1' => 0, 'arr2' => 0);
}

foreach ($arr1 as $item) {
    if (isset($result[$item])) {
        $result[$item]['arr1'] += 1;
    }
}

foreach ($arr2 as $item) {
    if (isset($result[$item])) {
        $result[$item]['arr2'] += 1;
    }
}</code>
Copy after login
Related labels:
php
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template