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?

Geo
  • 12,666
  • 4
  • 40
  • 55
  • can you post your 2 arrays ? – Maximus2012 Jul 25 '13 at 17:02
  • @Maximus2012 Why does it matter what's in the arrays? I don't think there's anything built-in that does this. But you can use `array_flip` on one of them, and then use a loop on the other that uses `array_key_exists`. – Barmar Jul 25 '13 at 17:04
  • in_array would internally loop through all of the values of one array for each value in the other so probably no savings there. – Orangepill Jul 25 '13 at 17:09
  • @Orangepill, thru **all** the values? Or will it return once the first match is encountered? – Geo Jul 25 '13 at 17:27
  • until first match. If the normal case is points of intersection to exist loop/array_search would probably yield better results on average. If you don't expect matches array intersect is going to be the way to go. – Orangepill Jul 25 '13 at 17:33
  • loop+array_search() VS loop+in_array()? Or that's the same thing? – Geo Jul 25 '13 at 17:37
  • in_array may have a (very) slight advantage. – Orangepill Jul 25 '13 at 17:45

2 Answers2

3

How about this?

foreach ($arr1 as $key => $val) {
    if (in_array($val, $arr2)){
        // do something, maybe return so you wouldn't need break
        break;
    }
}
mavili
  • 3,385
  • 4
  • 30
  • 46
  • yes, this was pretty much exactly what I had in mind. I was just hoping there might be a native function or a parameter for `array_intersect()` – Geo Jul 25 '13 at 17:29
0

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 
}