Question

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?

Was it helpful?

Solution

How about this?

foreach ($arr1 as $key => $val) {
    if (in_array($val, $arr2)){
        // do something, maybe return so you wouldn't need break
        break;
    }
}

OTHER TIPS

Just compare the first value?

$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 
} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top