6

I need to find out, in PHP, if an array has any of the values of the other array.

For example :

$search_values = array('cat', 'horse', 'dog');
$results = array('cat', 'horse');
if (in_array($search_values, $results))
    echo 'A value was found';

Of course, the above does not really work (in_array).

Basically, based on the above example, I want to check if in the $results array, there is either a cat, hourse or a dog.

Do I need to do a "foreach" in the 1st array, then do an "in_array" in the 2sd one, and return true; if it is found? Or is there a better way?

Frederic Hutow
  • 144
  • 1
  • 11

7 Answers7

15

You might want to use array_intersect()

$search_values = array('cat', 'horse', 'dog');
$results = array('cat', 'horse');

if ( count ( array_intersect($search_values, $results) ) > 0 ) {
    echo 'BINGO';
} else {
    echo 'NO MATCHES';
}
Zoltan Toth
  • 45,022
  • 11
  • 108
  • 129
4

array_intersect() will be slower in some cases with large arrays, because it return whole intersection which is unnecessary. Complexity will be O(n).

Code to just find one match:




     $arr1 = array('cat', 'dog');
        $arr2 = array('cow', 'horse', 'cat');

        // build hash map for one of arrays, O(n) time
        foreach ($arr2 as $v) {
            $arr2t[$v] = $v;
        }
        $arr2 = $arr2t;

        // search for at least one map, worst case O(n) time
        $found = false;
        foreach ($arr1 as $v) {
            if (isset($arr2[$v])) {
                $found = true;
                break;
            }
        }

TomTom
  • 1,669
  • 1
  • 11
  • 14
0

When using in_array you need to specify as the first value a NEEDLE which is a string. The second value is the array in which you want to check.

If you want to compare two arrays you need to use array_intersect.

Maude
  • 382
  • 2
  • 6
  • 21
0

Something like this:

return !empty(array_intersect($search_values, $result));
Herokiller
  • 2,560
  • 5
  • 29
  • 48
0

Use the array_intersect PHP function:

<?php

$search_values = array('cat', 'horse', 'dog');
$results = array('cat', 'horse');

$present = array_intersect( $search_values, $results );

if( count( $present ) )
{
    // your code
    echo 'A value was found';
    print_r( $present );
}
Fabio Mora
  • 4,939
  • 2
  • 16
  • 30
0

I think this will work. My MAMP setup is not on this mac so can't test.

$search_values = array('cat', 'horse', 'dog');
$results = array('cat', 'horse');
foreach($results as $k => $v){
 if(in_array($v, $search_values){
    $found = $found && true;
  }
}
Alex Reynolds
  • 6,090
  • 4
  • 23
  • 42
0

You can use following code :

$search_values = array('cat', 'horse', 'dog');
$results = array('cat', 'horse');
if (count(array_intersect($search_values, $results)) > 0 )
    echo 'A value was found';

Use array_intersect function.

Here is the working demo :

Nishu Tayal
  • 18,079
  • 8
  • 44
  • 90