38

Currently I have 2 array:

array(1, 2, 3, 4);
array(4, 5, 6, 7);

How can I check if there is at least one equal value in both of them? (The example above has 1 equal value => 4, so the function should return true).

Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156

1 Answers1

69

array_intersect()

returns an array containing all the values of array1 that are present in all the arguments. Note that keys are preserved

$a = array(1, 2, 3, 4);
$b = array(4, 5, 6, 7);
$c = array_intersect($a, $b);
if (count($c) > 0) {
    var_dump($c);
    //there is at least one equal value
}

you get

array(1) {
  [3]=>
  int(4)
}
Erenor Paz
  • 3,061
  • 4
  • 37
  • 44
macjohn
  • 1,755
  • 14
  • 18
  • then: `if (count($c)>0) doSomething();` – Alasdair Dec 30 '11 at 12:32
  • 5
    This is sub-optimal as the complete intersection is calculated, but you could stop as soon as one match is found. However, with small arrays, the efficiency of a built-in function will probably out-weigh the theoretical complexity issue. If you have large arrays you'll do better to sort them and then do a duel traverse removing the lowest from each until both empty or there is a match. – Robert Egginton May 11 '16 at 09:01
  • 9
    Ummm... just `if(array_intersect($a, $b))` – AbraCadaver Dec 18 '16 at 05:22
  • @RobertEgginton, you may want to traverse from the end of the array, removing the first element could force a `memmove`. That being said, already the sorts are going to be a killer. – Alexis Wilke Jan 28 '19 at 20:50