Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find if an array has at least 1 of the values

Tags:

arrays

php

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?

like image 264
Frederic Hutow Avatar asked Aug 08 '12 16:08

Frederic Hutow


2 Answers

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';
}
like image 55
Zoltan Toth Avatar answered Oct 25 '22 13:10

Zoltan Toth


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;
            }
        }

like image 25
TomTom Avatar answered Oct 25 '22 12:10

TomTom