简体   繁体   中英

Comparing two and three arrays for the same values contained anyhere within the array

I have 3 arrays. $eldest_range $second_range $third_range

$eldest_range = range($start_year1,$end_year1);
print_r($eldest_range);

$second_range = range($start_year2,$end_year2);
print_r($second_range);

$third_range = range($start_year3,$end_year3);
print_r($third_range);

Which returns: <br> Array ( [0] => 2030 [1] => 2031 [2] => 2032 [3] => 2033 [4] => 2034 [5] => 2035 ) <Br> Array ( [0] => 2032 [1] => 2033 [2] => 2034 [3] => 2035 [4] => 2036 [5] => 2037 ) <br> Array ( [0] => 2034 [1] => 2035 [2] => 2036 [3] => 2037 [4] => 2038 [5] => 2039 ) <Br>

I want compare these arrays. To check what if any of them are present within one another. So in the above case 1 & 2 share 2032, but 1,2 & 3 share 2034.

I would rather check them separately in pairs and then as a three. (1 & 2 - 1 & 3 - 2 & 3 - 1, 2 & 3)

Here's what I have tried. This is for Eldest to second:

$result=array_intersect_assoc($eldest_range, $second_range);
print_r($result);

which returns, nothing: array() and I have also tried..

$result=array_intersect_key($eldest_range, $second_range);
print_r($result);

which returns just the whole of $eldest_range

Array ( [0] => 2030 [1] => 2031 [2] => 2032 [3] => 2033 [4] => 2034 [5] => 2035 )

Am i using the wrong array_intersect() . I just want to see any values that are in 2 arrays. and 3 arrays (as above).

Thank you

Sometimes it is very useful to read a manual , which says that array_intersect_assoc

Computes the intersection of arrays with additional index check

Do you need this index check? Definitely no .

What you need is simple array_intersect :

$eldest_range = range(2030, 2035);
$second_range = range(2032, 2037);
$third_range = range(2034, 2039);
print_r(array_intersect($eldest_range, $second_range));   // [2032, 2033, 2034, 2035]
print_r(array_intersect($eldest_range, $second_range, $third_range)); // [2034, 2035]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM