2

I have 2 arrays to compare and find if there is at least a single value in common.

This works just fine:

$arr1 = array(1, 2, 3, 4, 5);
$arr2 = array(2, 3, 4, 5, 6);
if (array_intersect($arr1, $arr2)) {
    // good, at least one match found
}

However, the question is performance. It doesn't make sense to continue looping thru the arrays after the first match was found. Is there a native PHP function or a useful snippet to achieve this?

Will a combination of foreach() and in_array() do the trick?

4

2 回答 2

3

这个怎么样?

foreach ($arr1 as $key => $val) {
    if (in_array($val, $arr2)){
        // do something, maybe return so you wouldn't need break
        break;
    }
}
于 2013-07-25T17:08:41.613 回答
1

只比较第一个值?

$arr1 = array(1, 2, 3, 4, 5); 
$arr2 = array(2, 3, 4, 5, 6); 
if (array_intersect($arr1, $arr2)[0]) { 
    // good, at least one match found 
} 
于 2021-06-18T20:43:46.077 回答