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?
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';
}
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With